home *** CD-ROM | disk | FTP | other *** search
/ Chip 2007 January, February, March & April / Chip-Cover-CD-2007-02.iso / Pakiet bezpieczenstwa / mini Pentoo LiveCD 2006.1 / mpentoo-2006.1.iso / livecd.squashfs / usr / lib / mozilla-firefox / components / nsUpdateService.js < prev    next >
Text File  |  2006-05-08  |  93KB  |  2,814 lines

  1. //@line 41 "/var/tmp/portage/mozilla-firefox-1.5.0.3/work/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2.  
  3. const PREF_APP_UPDATE_ENABLED             = "app.update.enabled";
  4. const PREF_APP_UPDATE_AUTO                = "app.update.auto";
  5. const PREF_APP_UPDATE_MODE                = "app.update.mode";
  6. const PREF_APP_UPDATE_SILENT              = "app.update.silent";
  7. const PREF_APP_UPDATE_INTERVAL            = "app.update.interval";
  8. const PREF_APP_UPDATE_TIMER               = "app.update.timer";
  9. const PREF_APP_UPDATE_LOG_BRANCH          = "app.update.log.";
  10. const PREF_APP_UPDATE_URL                 = "app.update.url";
  11. const PREF_APP_UPDATE_URL_OVERRIDE        = "app.update.url.override";
  12. const PREF_APP_UPDATE_URL_DETAILS         = "app.update.url.details";
  13. const PREF_APP_UPDATE_CHANNEL             = "app.update.channel";
  14. const PREF_APP_UPDATE_SHOW_INSTALLED_UI   = "app.update.showInstalledUI";
  15. const PREF_APP_UPDATE_LASTUPDATETIME_FMT  = "app.update.lastUpdateTime.%ID%";
  16. const PREF_APP_EXTENSIONS_VERSION         = "app.extensions.version";
  17. const PREF_GENERAL_USERAGENT_LOCALE       = "general.useragent.locale";
  18. const PREF_APP_UPDATE_INCOMPATIBLE_MODE   = "app.update.incompatible.mode";
  19.  
  20. const URI_UPDATE_PROMPT_DIALOG  = "chrome://mozapps/content/update/updates.xul";
  21. const URI_UPDATE_HISTORY_DIALOG = "chrome://mozapps/content/update/history.xul";
  22. const URI_BRAND_PROPERTIES      = "chrome://branding/locale/brand.properties";
  23. const URI_UPDATES_PROPERTIES    = "chrome://mozapps/locale/update/updates.properties";
  24. const URI_UPDATE_NS             = "http://www.mozilla.org/2005/app-update";
  25.  
  26. const KEY_APPDIR          = "XCurProcD";
  27.  
  28. const DIR_UPDATES         = "updates";
  29. const FILE_UPDATE_STATUS  = "update.status";
  30. const FILE_UPDATE_ARCHIVE = "update.mar";
  31. const FILE_UPDATE_LOG     = "update.log"
  32. const FILE_UPDATES_DB     = "updates.xml";
  33. const FILE_UPDATE_ACTIVE  = "active-update.xml";
  34. const FILE_PERMS_TEST     = "update.test";
  35. const FILE_LAST_LOG       = "last-update.log";
  36.  
  37. const MODE_RDONLY   = 0x01;
  38. const MODE_WRONLY   = 0x02;
  39. const MODE_CREATE   = 0x08;
  40. const MODE_APPEND   = 0x10;
  41. const MODE_TRUNCATE = 0x20;
  42.  
  43. const PERMS_FILE      = 0644;
  44. const PERMS_DIRECTORY = 0755;
  45.  
  46. const STATE_NONE            = null;
  47. const STATE_DOWNLOADING     = "downloading";
  48. const STATE_PENDING         = "pending";
  49. const STATE_APPLYING        = "applying";
  50. const STATE_SUCCEEDED       = "succeeded";
  51. const STATE_DOWNLOAD_FAILED = "download-failed";
  52. const STATE_FAILED          = "failed";
  53.  
  54. // From updater/errors.h:
  55. const WRITE_ERROR = 7;
  56.  
  57. const DOWNLOAD_CHUNK_SIZE           = 65536;
  58. const DOWNLOAD_BACKGROUND_INTERVAL  = 60;  // seconds
  59. const DOWNLOAD_FOREGROUND_INTERVAL  = 0;
  60.  
  61. // Values for the PREF_APP_UPDATE_INCOMPATIBLE_MODE pref. See documentation in
  62. // code below. 
  63. const INCOMPATIBLE_MODE_NEWVERSIONS   = 0;
  64. const INCOMPATIBLE_MODE_NONEWVERSIONS = 1;
  65.  
  66. const POST_UPDATE_CONTRACTID = "@mozilla.org/updates/post-update;1";
  67.  
  68. const nsILocalFile            = Components.interfaces.nsILocalFile;
  69. const nsIUpdateService        = Components.interfaces.nsIUpdateService;
  70. const nsIUpdateItem           = Components.interfaces.nsIUpdateItem;
  71. const nsIPrefLocalizedString  = Components.interfaces.nsIPrefLocalizedString;
  72. const nsIIncrementalDownload  = Components.interfaces.nsIIncrementalDownload;
  73. const nsIFileInputStream      = Components.interfaces.nsIFileInputStream;
  74. const nsIFileOutputStream     = Components.interfaces.nsIFileOutputStream;
  75. const nsICryptoHash           = Components.interfaces.nsICryptoHash;
  76.  
  77. const Node = Components.interfaces.nsIDOMNode;
  78.  
  79. var gApp        = null;
  80. var gPref       = null;
  81. var gOS         = null;
  82. var gABI        = null;
  83. var gConsole    = null;
  84. var gLogEnabled = { };
  85.  
  86. /**
  87.  * Logs a string to the error console. 
  88.  * @param   string
  89.  *          The string to write to the error console..
  90.  */  
  91. function LOG(module, string) {
  92.   if (module in gLogEnabled) {
  93.     dump("*** " + module + ":" + string + "\n");
  94.     gConsole.logStringMessage(string);
  95.   }
  96. }
  97.  
  98. /**
  99.  * Convert a string containing binary values to hex.
  100.  */
  101. function binaryToHex(input) {
  102.   var result = "";
  103.   for (var i = 0; i < input.length; ++i) {
  104.     var hex = input.charCodeAt(i).toString(16);
  105.     if (hex.length == 1)
  106.       hex = "0" + hex;
  107.     result += hex;
  108.   }
  109.   return result;
  110. }
  111.  
  112. /**
  113.  * Gets a File URL spec for a nsIFile
  114.  * @param   file
  115.  *          The file to get a file URL spec to
  116.  * @returns The file URL spec to the file
  117.  */
  118. function getURLSpecFromFile(file) {
  119.   var ioServ = Components.classes["@mozilla.org/network/io-service;1"]
  120.                          .getService(Components.interfaces.nsIIOService);
  121.   var fph = ioServ.getProtocolHandler("file")
  122.                   .QueryInterface(Components.interfaces.nsIFileProtocolHandler);
  123.   return fph.getURLSpecFromFile(file);
  124. }
  125.  
  126. /**
  127.  * Gets the specified directory at the specified hierarchy under a 
  128.  * Directory Service key. 
  129.  * @param   key
  130.  *          The Directory Service Key to start from
  131.  * @param   pathArray
  132.  *          An array of path components to locate beneath the directory 
  133.  *          specified by |key|
  134.  * @return  nsIFile object for the location specified. If the directory
  135.  *          requested does not exist, it is created, along with any
  136.  *          parent directories that need to be created.
  137.  */
  138. function getDir(key, pathArray) {
  139.   return getDirInternal(key, pathArray, true);
  140. }
  141.  
  142. /**
  143.  * Gets the specified directory at the speciifed hierarchy under a 
  144.  * Directory Service key. 
  145.  * @param   key
  146.  *          The Directory Service Key to start from
  147.  * @param   pathArray
  148.  *          An array of path components to locate beneath the directory 
  149.  *          specified by |key|
  150.  * @return  nsIFile object for the location specified. If the directory
  151.  *          requested does not exist, it is NOT created.
  152.  */
  153. function getDirNoCreate(key, pathArray) {
  154.   return getDirInternal(key, pathArray, false);
  155. }
  156.  
  157. /**
  158.  * Gets the specified directory at the speciifed hierarchy under a 
  159.  * Directory Service key. 
  160.  * @param   key
  161.  *          The Directory Service Key to start from
  162.  * @param   pathArray
  163.  *          An array of path components to locate beneath the directory 
  164.  *          specified by |key|
  165.  * @param   shouldCreate
  166.  *          true if the directory hierarchy specified in |pathArray|
  167.  *          should be created if it does not exist,
  168.  *          false otherwise.
  169.  * @return  nsIFile object for the location specified. 
  170.  */
  171. function getDirInternal(key, pathArray, shouldCreate) {
  172.   var fileLocator = Components.classes["@mozilla.org/file/directory_service;1"]
  173.                               .getService(Components.interfaces.nsIProperties);
  174.   var dir = fileLocator.get(key, Components.interfaces.nsIFile);
  175.   for (var i = 0; i < pathArray.length; ++i) {
  176.     dir.append(pathArray[i]);
  177.     if (shouldCreate && !dir.exists())
  178.       dir.create(nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  179.   }
  180.   return dir;
  181. }
  182.  
  183. /**
  184.  * Gets the file at the speciifed hierarchy under a Directory Service key.
  185.  * @param   key
  186.  *          The Directory Service Key to start from
  187.  * @param   pathArray
  188.  *          An array of path components to locate beneath the directory 
  189.  *          specified by |key|. The last item in this array must be the
  190.  *          leaf name of a file.
  191.  * @return  nsIFile object for the file specified. The file is NOT created
  192.  *          if it does not exist, however all required directories along 
  193.  *          the way are.
  194.  */
  195. function getFile(key, pathArray) {
  196.   var file = getDir(key, pathArray.slice(0, -1));
  197.   file.append(pathArray[pathArray.length - 1]);
  198.   return file;
  199. }
  200.  
  201. /**
  202.  * Closes a Safe Output Stream
  203.  * @param   fos
  204.  *          The Safe Output Stream to close
  205.  */
  206. function closeSafeOutputStream(fos) {
  207.   if (fos instanceof Components.interfaces.nsISafeOutputStream) {
  208.     try {
  209.       fos.finish();
  210.     }
  211.     catch (e) {
  212.       fos.close();
  213.     }
  214.   }
  215.   else
  216.     fos.close();
  217. }
  218.  
  219. /**
  220.  * Returns human readable status text from the updates.properties bundle
  221.  * based on an error code
  222.  * @param   code
  223.  *          The error code to look up human readable status text for
  224.  * @param   defaultCode
  225.  *          The default code to look up should human readable status text
  226.  *          not exist for |code|
  227.  * @returns A human readable status text string
  228.  */
  229. function getStatusTextFromCode(code, defaultCode) {
  230.   var sbs = 
  231.       Components.classes["@mozilla.org/intl/stringbundle;1"].
  232.       getService(Components.interfaces.nsIStringBundleService);
  233.   var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  234.   var reason = updateBundle.GetStringFromName("checker_error-" + defaultCode);
  235.   try {
  236.     reason = updateBundle.GetStringFromName("checker_error-" + code);
  237.     LOG("General", "Transfer Error: " + reason + ", code: " + code);
  238.   }
  239.   catch (e) {
  240.     // Use the default reason
  241.     LOG("General", "Transfer Error: " + reason + ", code: " + defaultCode);
  242.   }
  243.   return reason;
  244. }
  245.  
  246. /**
  247.  * Get the Active Updates directory
  248.  * @returns The active updates directory, as a nsIFile object
  249.  */
  250. function getUpdatesDir() {
  251.   // Right now, we only support downloading one patch at a time, so we always
  252.   // use the same target directory.
  253.   var fileLocator =
  254.       Components.classes["@mozilla.org/file/directory_service;1"].
  255.       getService(Components.interfaces.nsIProperties);
  256.   var appDir = fileLocator.get(KEY_APPDIR, Components.interfaces.nsIFile);
  257.   appDir.append(DIR_UPDATES);
  258.   appDir.append("0");
  259.   if (!appDir.exists())
  260.     appDir.create(nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  261.   return appDir;
  262. }
  263.  
  264. /**
  265.  * Reads the update state from the update.status file in the specified
  266.  * directory.
  267.  * @param   dir
  268.  *          The dir to look for an update.status file in
  269.  * @returns The status value of the update.
  270.  */
  271. function readStatusFile(dir) {
  272.   var statusFile = dir.clone();
  273.   statusFile.append(FILE_UPDATE_STATUS);
  274.   LOG("General", "Reading Status File: " + statusFile.path);
  275.   return readStringFromFile(statusFile) || STATE_NONE;
  276. }
  277.  
  278. /**
  279.  * Writes the current update operation/state to a file in the patch 
  280.  * directory, indicating to the patching system that operations need
  281.  * to be performed.
  282.  * @param   dir
  283.  *          The patch directory where the update.status file should be 
  284.  *          written.
  285.  * @param   state
  286.  *          The state value to write.
  287.  */
  288. function writeStatusFile(dir, state) {
  289.   var statusFile = dir.clone();
  290.   statusFile.append(FILE_UPDATE_STATUS);
  291.   writeStringToFile(statusFile, state);
  292. }
  293.  
  294. /**
  295.  * Removes the Updates Directory
  296.  */
  297. function cleanUpUpdatesDir() {
  298.   // Bail out if we don't have appropriate permissions
  299.   var updateDir;
  300.   try {
  301.     updateDir = getUpdatesDir();
  302.   }
  303.   catch (e) {
  304.     return;
  305.   }
  306.         
  307.   var e = updateDir.directoryEntries;
  308.   while (e.hasMoreElements()) {
  309.     var f = e.getNext().QueryInterface(Components.interfaces.nsIFile);
  310.     // Preserve the last update log file for debugging purposes
  311.     if (f.leafName == FILE_UPDATE_LOG) {
  312.       try {
  313.         var dir = f.parent.parent;
  314.         var logFile = dir.clone();
  315.         logFile.append(FILE_LAST_LOG);
  316.         if (logFile.exists())
  317.           logFile.remove(false);
  318.         f.copyTo(dir, FILE_LAST_LOG);
  319.       }
  320.       catch (e) {
  321.         LOG("General", "Failed to copy file: " + f.path);
  322.       }
  323.     }
  324.     // Now, recursively remove this file.  The recusive removal is really
  325.     // only needed on Mac OSX because this directory will contain a copy of
  326.     // updater.app, which is itself a directory.
  327.     try {
  328.       f.remove(true);
  329.     }
  330.     catch (e) {
  331.       LOG("General", "Failed to remove file: " + f.path);
  332.     }
  333.   }
  334.   try {
  335.     updateDir.remove(false);
  336.   } catch (e) {
  337.     LOG("General", "Failed to remove update directory: " + updateDir.path + 
  338.         " - This is almost always bad. Exception = " + e);
  339.     throw e;
  340.   }
  341. }
  342.  
  343. /**
  344.  * Clean up updates list and the updates directory.
  345.  */
  346. function cleanupActiveUpdate() {
  347.   // Move the update from the Active Update list into the Past Updates list.
  348.   var um = 
  349.       Components.classes["@mozilla.org/updates/update-manager;1"].
  350.       getService(Components.interfaces.nsIUpdateManager);
  351.   um.activeUpdate = null;
  352.   um.saveUpdates();
  353.  
  354.   // Now trash the updates directory, since we're done with it
  355.   cleanUpUpdatesDir();
  356. }
  357.  
  358. /**
  359.  * Gets a preference value, handling the case where there is no default.
  360.  * @param   func
  361.  *          The name of the preference function to call, on nsIPrefBranch
  362.  * @param   preference
  363.  *          The name of the preference
  364.  * @param   defaultValue
  365.  *          The default value to return in the event the preference has 
  366.  *          no setting
  367.  * @returns The value of the preference, or undefined if there was no
  368.  *          user or default value.
  369.  */
  370. function getPref(func, preference, defaultValue) {
  371.   try {
  372.     return gPref[func](preference);
  373.   }
  374.   catch (e) {
  375.   }
  376.   return defaultValue;
  377. }
  378.  
  379. /**
  380.  * Gets the current value of the locale.  It's possible for this preference to
  381.  * be localized, so we have to do a little extra work here.  Similar code
  382.  * exists in nsHttpHandler.cpp when building the UA string.
  383.  */
  384. function getLocale() {
  385.   try {
  386.     return gPref.getComplexValue(PREF_GENERAL_USERAGENT_LOCALE,
  387.                                  nsIPrefLocalizedString).data;
  388.   } catch (e) {}
  389.  
  390.   return gPref.getCharPref(PREF_GENERAL_USERAGENT_LOCALE);
  391. }
  392.  
  393. /**
  394.  * An enumeration of items in a JS array.
  395.  * @constructor
  396.  */
  397. function ArrayEnumerator(aItems) {
  398.   this._index = 0;
  399.   if (aItems) {
  400.     for (var i = 0; i < aItems.length; ++i) {
  401.       if (!aItems[i])
  402.         aItems.splice(i, 1);      
  403.     }
  404.   }
  405.   this._contents = aItems;
  406. }
  407.  
  408. ArrayEnumerator.prototype = {
  409.   _index: 0,
  410.   _contents: [],
  411.   
  412.   hasMoreElements: function() {
  413.     return this._index < this._contents.length;
  414.   },
  415.   
  416.   getNext: function() {
  417.     return this._contents[this._index++];      
  418.   }
  419. };
  420.  
  421. /**
  422.  * Trims a prefix from a string.
  423.  * @param   string
  424.  *          The source string
  425.  * @param   prefix
  426.  *          The prefix to remove.
  427.  * @returns The suffix (string - prefix)
  428.  */
  429. function stripPrefix(string, prefix) {
  430.   return string.substr(prefix.length);
  431. }
  432.  
  433. /**
  434.  * Writes a string of text to a file.  A newline will be appended to the data
  435.  * written to the file.  This function only works with ASCII text.
  436.  */
  437. function writeStringToFile(file, text) {
  438.   var fos =
  439.       Components.classes["@mozilla.org/network/safe-file-output-stream;1"].
  440.       createInstance(nsIFileOutputStream);
  441.   var modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  442.   if (!file.exists()) 
  443.     file.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  444.   fos.init(file, modeFlags, PERMS_FILE, 0);
  445.   text += "\n";
  446.   fos.write(text, text.length);    
  447.   closeSafeOutputStream(fos);
  448. }
  449.  
  450. /**
  451.  * Reads a string of text from a file.  A trailing newline will be removed
  452.  * before the result is returned.  This function only works with ASCII text.
  453.  */
  454. function readStringFromFile(file) {
  455.   var fis =
  456.       Components.classes["@mozilla.org/network/file-input-stream;1"].
  457.       createInstance(nsIFileInputStream);
  458.   var modeFlags = MODE_RDONLY;
  459.   if (!file.exists())
  460.     return null;
  461.   fis.init(file, modeFlags, PERMS_FILE, 0);
  462.   var sis =
  463.       Components.classes["@mozilla.org/scriptableinputstream;1"].
  464.       createInstance(Components.interfaces.nsIScriptableInputStream);
  465.   sis.init(fis);
  466.   var text = sis.read(sis.available());
  467.   sis.close();
  468.   if (text[text.length - 1] == "\n")
  469.     text = text.slice(0, -1);
  470.   return text;
  471. }
  472.  
  473. /**
  474.  * Update Patch
  475.  * @param   patch
  476.  *          A <patch> element to initialize this object with
  477.  * @constructor
  478.  */
  479. function UpdatePatch(patch) {
  480.   this._properties = {};
  481.   for (var i = 0; i < patch.attributes.length; ++i) {
  482.     var attr = patch.attributes.item(i);
  483.     attr.QueryInterface(Components.interfaces.nsIDOMAttr);
  484.     switch (attr.name) {
  485.     case "selected":
  486.       this.selected = attr.value == "true";
  487.       break;
  488.     default:
  489.       this[attr.name] = attr.value;
  490.       break;
  491.     };
  492.   }
  493. }
  494. UpdatePatch.prototype = {
  495.   /**
  496.    * See nsIUpdateService.idl
  497.    */
  498.   serialize: function(updates) {
  499.     var patch = updates.createElementNS(URI_UPDATE_NS, "patch");
  500.     patch.setAttribute("type", this.type);
  501.     patch.setAttribute("URL", this.URL);
  502.     patch.setAttribute("hashFunction", this.hashFunction);
  503.     patch.setAttribute("hashValue", this.hashValue);
  504.     patch.setAttribute("size", this.size);
  505.     patch.setAttribute("selected", this.selected);
  506.     patch.setAttribute("state", this.state);
  507.     
  508.     for (var p in this._properties) {
  509.       if (this._properties[p].present)
  510.         patch.setAttribute(p, this._properties[p].data);
  511.     }
  512.     
  513.     return patch; 
  514.   },
  515.   
  516.   /**
  517.    * A hash of custom properties
  518.    */
  519.   _properties: null,
  520.   
  521.   /**
  522.    * See nsIWritablePropertyBag.idl
  523.    */
  524.   setProperty: function(name, value) {
  525.     this._properties[name] = { data: value, present: true };
  526.   },
  527.   
  528.   /**
  529.    * See nsIWritablePropertyBag.idl
  530.    */
  531.   deleteProperty: function(name) {
  532.     if (name in this._properties)
  533.       this._properties[name].present = false;
  534.     else
  535.       throw Components.results.NS_ERROR_FAILURE;
  536.   },
  537.   
  538.   /**
  539.    * See nsIPropertyBag.idl
  540.    */
  541.   get enumerator() {
  542.     var properties = [];
  543.     for (var p in this._properties)
  544.       properties.push(this._properties[p].data);
  545.     return new ArrayEnumerator(properties);
  546.   },
  547.   
  548.   /**
  549.    * See nsIPropertyBag.idl
  550.    */
  551.   getProperty: function(name) {
  552.     if (name in this._properties &&
  553.         this._properties[name].present)
  554.       return this._properties[name].data;
  555.     throw Components.results.NS_ERROR_FAILURE;
  556.   },
  557.   
  558.   /**
  559.    * Returns whether or not the update.status file for this patch exists at the 
  560.    * appropriate location. 
  561.    */
  562.   get statusFileExists() {
  563.     var statusFile = getUpdatesDir();
  564.     statusFile.append(FILE_UPDATE_STATUS);
  565.     return statusFile.exists();
  566.   },
  567.   
  568.   /**
  569.    * See nsIUpdateService.idl
  570.    */
  571.   get state() {
  572.     if (!this.statusFileExists)
  573.       return STATE_NONE;
  574.     return this._properties.state;
  575.   },
  576.   set state(val) {
  577.     this._properties.state = val;
  578.   },
  579.   
  580.   /**
  581.    * See nsISupports.idl
  582.    */
  583.   QueryInterface: function(iid) {
  584.     if (!iid.equals(Components.interfaces.nsIUpdatePatch) &&
  585.         !iid.equals(Components.interfaces.nsIPropertyBag) && 
  586.         !iid.equals(Components.interfaces.nsIWritablePropertyBag) && 
  587.         !iid.equals(Components.interfaces.nsISupports))
  588.       throw Components.results.NS_ERROR_NO_INTERFACE;
  589.     return this;
  590.   }
  591. };
  592.  
  593. /**
  594.  * Update
  595.  * Implements nsIUpdate
  596.  * @param   update
  597.  *          An <update> element to initialize this object with
  598.  * @constructor
  599.  */
  600. function Update(update) {
  601.   this._properties = {};
  602.   this._patches = [];
  603.   this.installDate = 0;
  604.   this.isCompleteUpdate = false;
  605.  
  606.   // Null <update>, assume this is a message container and do no 
  607.   // further initialization
  608.   if (!update)
  609.     return;
  610.     
  611.   for (var i = 0; i < update.childNodes.length; ++i) {
  612.     var patchElement = update.childNodes.item(i);
  613.     if (patchElement.nodeType != Node.ELEMENT_NODE ||
  614.         patchElement.localName != "patch")
  615.       continue;
  616.  
  617.     patchElement.QueryInterface(Components.interfaces.nsIDOMElement);
  618.     this._patches.push(new UpdatePatch(patchElement));
  619.   }
  620.  
  621.   for (var i = 0; i < update.attributes.length; ++i) {
  622.     var attr = update.attributes.item(i);
  623.     attr.QueryInterface(Components.interfaces.nsIDOMAttr);
  624.     if (attr.name == "installDate" && attr.value) 
  625.       this.installDate = parseInt(attr.value);
  626.     else if (attr.name == "isCompleteUpdate")
  627.       this.isCompleteUpdate = attr.value == "true";
  628.     else if (attr.name == "isSecurityUpdate")
  629.       this.isSecurityUpdate = attr.value == "true";
  630.     else if (attr.name == "detailsURL")
  631.       this._detailsURL = attr.value;
  632.     else
  633.       this[attr.name] = attr.value;
  634.   }
  635.   
  636.   // The Update Name is either the string provided by the <update> element, or
  637.   // the string: "<App Name> <Update App Version>"
  638.   var name = "";
  639.   if (update.hasAttribute("name"))
  640.     name = update.getAttribute("name");
  641.   else {
  642.     var sbs = Components.classes["@mozilla.org/intl/stringbundle;1"]
  643.                         .getService(Components.interfaces.nsIStringBundleService);
  644.     var brandBundle = sbs.createBundle(URI_BRAND_PROPERTIES);
  645.     var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  646.     var appName = brandBundle.GetStringFromName("brandShortName");
  647.     name = updateBundle.formatStringFromName("updateName", 
  648.                                              [appName, this.version], 2);
  649.   }
  650.   this.name = name;
  651. }
  652. Update.prototype = {
  653.   /**
  654.    * See nsIUpdateService.idl
  655.    */
  656.   get patchCount() {
  657.     return this._patches.length;
  658.   },
  659.   
  660.   /**
  661.    * See nsIUpdateService.idl
  662.    */
  663.   getPatchAt: function(index) {
  664.     return this._patches[index];
  665.   },
  666.  
  667.   /**
  668.    * See nsIUpdateService.idl
  669.    * 
  670.    * We use a copy of the state cached on this object in |_state| only when 
  671.    * there is no selected patch, i.e. in the case when we could not load 
  672.    * |.activeUpdate| from the update manager for some reason but still have
  673.    * the update.status file to work with. 
  674.    */
  675.   _state: "",
  676.   set state(state) {
  677.     if (this.selectedPatch)
  678.       this.selectedPatch.state = state;
  679.     this._state = state;
  680.     return state;
  681.   },
  682.   get state() {
  683.     if (this.selectedPatch)
  684.       return this.selectedPatch.state;
  685.     return this._state;
  686.   },
  687.  
  688.   /**
  689.    * See nsIUpdateService.idl
  690.    */
  691.   errorCode: 0,
  692.     
  693.   /**
  694.    * See nsIUpdateService.idl
  695.    */
  696.   get selectedPatch() {
  697.     for (var i = 0; i < this.patchCount; ++i) {
  698.       if (this._patches[i].selected)
  699.         return this._patches[i];
  700.     }
  701.     return null;
  702.   },
  703.   
  704.   /**
  705.    * See nsIUpdateService.idl
  706.    */
  707.   get detailsURL() {
  708.     if (!this._detailsURL) {
  709.       try {
  710.         // Try using a default details URL supplied by the distribution
  711.         // if the update XML does not supply one.
  712.         return gPref.getComplexValue(PREF_APP_UPDATE_URL_DETAILS,
  713.                                      nsIPrefLocalizedString).data;
  714.       }
  715.       catch (e) {
  716.       }
  717.     }
  718.     return this._detailsURL || "";
  719.   },
  720.   
  721.   /**
  722.    * See nsIUpdateService.idl
  723.    */
  724.   serialize: function(updates) {
  725.     var update = updates.createElementNS(URI_UPDATE_NS, "update");
  726.     update.setAttribute("type", this.type);
  727.     update.setAttribute("name", this.name);
  728.     update.setAttribute("version", this.version);
  729.     update.setAttribute("extensionVersion", this.extensionVersion);
  730.     update.setAttribute("detailsURL", this.detailsURL);
  731.     update.setAttribute("licenseURL", this.licenseURL);
  732.     update.setAttribute("serviceURL", this.serviceURL);
  733.     update.setAttribute("installDate", this.installDate);
  734.     update.setAttribute("statusText", this.statusText);
  735.     update.setAttribute("buildID", this.buildID);
  736.     update.setAttribute("isCompleteUpdate", this.isCompleteUpdate);
  737.     updates.documentElement.appendChild(update);
  738.     
  739.     for (var p in this._properties) {
  740.       if (this._properties[p].present)
  741.         update.setAttribute(p, this._properties[p].data);
  742.     }
  743.     
  744.     for (var i = 0; i < this.patchCount; ++i)
  745.       update.appendChild(this.getPatchAt(i).serialize(updates));
  746.     
  747.     return update;
  748.   },
  749.    
  750.   /**
  751.    * A hash of custom properties
  752.    */
  753.   _properties: null,
  754.   
  755.   /**
  756.    * See nsIWritablePropertyBag.idl
  757.    */
  758.   setProperty: function(name, value) {
  759.     this._properties[name] = { data: value, present: true };
  760.   },
  761.   
  762.   /**
  763.    * See nsIWritablePropertyBag.idl
  764.    */
  765.   deleteProperty: function(name) {
  766.     if (name in this._properties)
  767.       this._properties[name].present = false;
  768.     else
  769.       throw Components.results.NS_ERROR_FAILURE;
  770.   },
  771.   
  772.   /**
  773.    * See nsIPropertyBag.idl
  774.    */
  775.   get enumerator() {
  776.     var properties = [];
  777.     for (var p in this._properties)
  778.       properties.push(this._properties[p].data);
  779.     return new ArrayEnumerator(properties);
  780.   },
  781.   
  782.   /**
  783.    * See nsIPropertyBag.idl
  784.    */
  785.   getProperty: function(name) {
  786.     if (name in this._properties &&
  787.         this._properties[name].present)
  788.       return this._properties[name].data;
  789.     throw Components.results.NS_ERROR_FAILURE;
  790.   },
  791.   
  792.   /**
  793.    * See nsISupports.idl
  794.    */
  795.   QueryInterface: function(iid) {
  796.     if (!iid.equals(Components.interfaces.nsIUpdate) &&
  797.         !iid.equals(Components.interfaces.nsIPropertyBag) &&
  798.         !iid.equals(Components.interfaces.nsIWritablePropertyBag) &&
  799.         !iid.equals(Components.interfaces.nsISupports))
  800.       throw Components.results.NS_ERROR_NO_INTERFACE;
  801.     return this;
  802.   }
  803. }; 
  804.  
  805. /**
  806.  * UpdateService
  807.  * A Service for managing the discovery and installation of software updates.
  808.  * @constructor
  809.  */
  810. function UpdateService() {
  811.   gApp  = Components.classes["@mozilla.org/xre/app-info;1"]
  812.                     .getService(Components.interfaces.nsIXULAppInfo)
  813.                     .QueryInterface(Components.interfaces.nsIXULRuntime);
  814.   gPref = Components.classes["@mozilla.org/preferences-service;1"]
  815.                     .getService(Components.interfaces.nsIPrefBranch2);
  816.   gOS   = Components.classes["@mozilla.org/observer-service;1"]
  817.                     .getService(Components.interfaces.nsIObserverService);
  818.   gConsole = Components.classes["@mozilla.org/consoleservice;1"]
  819.                        .getService(Components.interfaces.nsIConsoleService);  
  820.  
  821.   // Not all builds have a known ABI
  822.   try {
  823.     gABI = gApp.XPCOMABI;
  824.   }
  825.   catch (e) {
  826.     LOG("UpdateService", "XPCOM ABI unknown: updates are not possible.");
  827.   }
  828.  
  829. //@line 877 "/var/tmp/portage/mozilla-firefox-1.5.0.3/work/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  830.  
  831.   // Start the update timer only after a profile has been selected so that the
  832.   // appropriate values for the update check are read from the user's profile.  
  833.   gOS.addObserver(this, "profile-after-change", false);
  834.  
  835.   // Observe xpcom-shutdown to unhook pref branch observers above to avoid 
  836.   // shutdown leaks.
  837.   gOS.addObserver(this, "xpcom-shutdown", false);
  838. }
  839.  
  840. UpdateService.prototype = {
  841.   /**
  842.    * The downloader we are using to download updates. There is only ever one of
  843.    * these.
  844.    */
  845.   _downloader: null,
  846.  
  847.   /**
  848.    * Handle Observer Service notifications
  849.    * @param   subject
  850.    *          The subject of the notification
  851.    * @param   topic
  852.    *          The notification name
  853.    * @param   data
  854.    *          Additional data
  855.    */
  856.   observe: function(subject, topic, data) {
  857.     switch (topic) {
  858.     case "profile-after-change":
  859.       gOS.removeObserver(this, "profile-after-change");
  860.       this._start();
  861.       break;
  862.     case "xpcom-shutdown":
  863.       gOS.removeObserver(this, "xpcom-shutdown");
  864.       
  865.       // Release Services
  866.       gApp      = null;
  867.       gPref     = null;
  868.       gOS       = null;
  869.       gConsole  = null;
  870.       break;
  871.     }
  872.   },
  873.   
  874.   /**
  875.    * Start the Update Service
  876.    */
  877.   _start: function() {
  878.     // Start logging
  879.     this._initLoggingPrefs();
  880.     
  881.     // Clean up any extant updates
  882.     this._postUpdateProcessing();
  883.  
  884.     // Register a background update check timer
  885.     var tm = 
  886.         Components.classes["@mozilla.org/updates/timer-manager;1"]
  887.                   .getService(Components.interfaces.nsIUpdateTimerManager);
  888.     var interval = getPref("getIntPref", PREF_APP_UPDATE_INTERVAL, 86400);
  889.     tm.registerTimer("background-update-timer", this, interval);
  890.  
  891.     // Resume fetching...
  892.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  893.                         .getService(Components.interfaces.nsIUpdateManager);
  894.     var activeUpdate = um.activeUpdate;
  895.     if (activeUpdate) {
  896.       var status = this.downloadUpdate(activeUpdate, true);
  897.       if (status == STATE_NONE)
  898.         cleanupActiveUpdate();
  899.     }
  900.   },
  901.   
  902.   /**
  903.    * Perform post-processing on updates lingering in the updates directory
  904.    * from a previous browser session - either report install failures (and
  905.    * optionally attempt to fetch a different version if appropriate) or 
  906.    * notify the user of install success.
  907.    */
  908.   _postUpdateProcessing: function() {
  909.     // Detect installation failures and notify
  910.     
  911.     // Bail out if we don't have appropriate permissions
  912.     if (!this.canUpdate)
  913.       return;
  914.       
  915.     var status = readStatusFile(getUpdatesDir()); 
  916.  
  917.     // Make sure to cleanup after an update that failed for an unknown reason
  918.     if (status == "null")
  919.       status = null;
  920.  
  921.     if (status == STATE_DOWNLOADING) {
  922.       LOG("UpdateService", "_postUpdateProcessing: Downloading patch, resuming...");
  923.     }
  924.     else if (status != null) {
  925.       // null status means the update.status file is not present, because either:
  926.       // 1) no update was performed, and so there's no UI to show
  927.       // 2) an update was attempted but failed during checking, transfer or 
  928.       //    verification, and was cleaned up at that point, and UI notifying of
  929.       //    that error was shown at that stage. 
  930.       var um = 
  931.           Components.classes["@mozilla.org/updates/update-manager;1"].
  932.           getService(Components.interfaces.nsIUpdateManager);
  933.       var prompter = 
  934.           Components.classes["@mozilla.org/updates/update-prompt;1"].
  935.           createInstance(Components.interfaces.nsIUpdatePrompt);
  936.  
  937.       var shouldCleanup = true;
  938.       var update = um.activeUpdate;
  939.       if (!update) {
  940.         if ((status == STATE_SUCCEEDED) && (um.updateCount >= 1))
  941.           update = um.getUpdateAt(0);
  942.         else
  943.           update = new Update(null);
  944.       }
  945.       update.state = status;
  946.       var sbs = 
  947.           Components.classes["@mozilla.org/intl/stringbundle;1"].
  948.           getService(Components.interfaces.nsIStringBundleService);
  949.       var bundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  950.       if (status == STATE_SUCCEEDED) {
  951.         update.statusText = bundle.GetStringFromName("installSuccess");
  952.         
  953.         // Dig through the update history to find the patch that was just
  954.         // installed and update its metadata.
  955.         for (var i = 0; i < um.updateCount; ++i) {
  956.           var umUpdate = um.getUpdateAt(i);
  957.           if (umUpdate && umUpdate.version == update.version &&
  958.                           umUpdate.buildID == update.buildID) {
  959.             umUpdate.statusText = update.statusText;
  960.             break;
  961.           }
  962.         }
  963.  
  964.         LOG("UpdateService", "_postUpdateProcessing: Install Succeeded, Showing UI");
  965.         prompter.showUpdateInstalled(update);
  966.  
  967.         // Perform platform-specific post-update processing.
  968.         if (POST_UPDATE_CONTRACTID in Components.classes) {
  969.           Components.classes[POST_UPDATE_CONTRACTID].
  970.               createInstance(Components.interfaces.nsIRunnable).run();
  971.         }
  972.         
  973.         // Done with this update. Clean it up.
  974.         cleanupActiveUpdate();
  975.       }
  976.       else {
  977.         // If we hit an error, then the error code will be included in the
  978.         // status string following a colon.  If we had an I/O error, then we
  979.         // assume that the patch is not invalid, and we restage the patch so
  980.         // that it can be attempted again the next time we restart.
  981.         var ary = status.split(": ");
  982.         update.state = ary[0];
  983.         if (update.state == STATE_FAILED && ary[1]) {
  984.           update.errorCode = ary[1];
  985.           if (update.errorCode == WRITE_ERROR) {
  986.             prompter.showUpdateError(update);
  987.             writeStatusFile(getUpdatesDir(), update.state = STATE_PENDING);
  988.             return;
  989.           }
  990.         }
  991.  
  992.         // Something went wrong with the patch application process.
  993.         cleanupActiveUpdate();
  994.  
  995.         update.statusText = bundle.GetStringFromName("patchApplyFailure");
  996.         var oldType = update.selectedPatch ? update.selectedPatch.type 
  997.                                            : "complete";
  998.         if (update.selectedPatch && oldType == "partial") {
  999.           // Partial patch application failed, try downloading the complete
  1000.           // update in the background instead.
  1001.           LOG("UpdateService", "_postUpdateProcessing: Install of Partial Patch " + 
  1002.               "failed, downloading Complete Patch and maybe showing UI");
  1003.           var status = this.downloadUpdate(update, true);
  1004.           if (status == STATE_NONE)
  1005.             cleanupActiveUpdate();
  1006.         }
  1007.         else {
  1008.           LOG("UpdateService", "_postUpdateProcessing: Install of Complete or " + 
  1009.               "only patch failed. Showing error.");
  1010.         }
  1011.         update.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  1012.         update.setProperty("patchingFailed", oldType);
  1013.         prompter.showUpdateError(update);
  1014.       }
  1015.     }
  1016.     else {
  1017.       LOG("UpdateService", "_postUpdateProcessing: No Status, No Update");
  1018.     }
  1019.   },
  1020.  
  1021.   /**
  1022.    * Initialize Logging preferences, formatted like so:
  1023.    *  app.update.log.<moduleName> = <true|false>
  1024.    */
  1025.   _initLoggingPrefs: function() {
  1026.     try {
  1027.       var ps = Components.classes["@mozilla.org/preferences-service;1"]
  1028.                         .getService(Components.interfaces.nsIPrefService);
  1029.       var logBranch = ps.getBranch(PREF_APP_UPDATE_LOG_BRANCH);
  1030.       var modules = logBranch.getChildList("", { value: 0 });
  1031.  
  1032.       for (var i = 0; i < modules.length; ++i) {
  1033.         if (logBranch.prefHasUserValue(modules[i]))
  1034.           gLogEnabled[modules[i]] = logBranch.getBoolPref(modules[i]);
  1035.       }
  1036.     }
  1037.     catch (e) {
  1038.     }
  1039.   },
  1040.   
  1041.   /**
  1042.    *
  1043.    */
  1044.   _needsToPromptForUpdate: function(updates) {
  1045.     // First, check for Extension incompatibilities. These trump any preference
  1046.     // settings.
  1047.     var em = Components.classes["@mozilla.org/extensions/manager;1"]
  1048.                        .getService(Components.interfaces.nsIExtensionManager);
  1049.     var incompatibleList = { };
  1050.     for (var i = 0; i < updates.length; ++i) {
  1051.       var count = {};
  1052.       em.getIncompatibleItemList(gApp.ID, updates[i].extensionVersion,
  1053.                                  nsIUpdateItem.TYPE_ADDON, false, count);
  1054.       if (count.value > 0)
  1055.         return true;
  1056.     }
  1057.  
  1058.     // Now, inspect user preferences.
  1059.     
  1060.     // No prompt necessary, silently update...
  1061.     return false;
  1062.   },
  1063.   
  1064.   /**
  1065.    * Notified when a timer fires
  1066.    * @param   timer
  1067.    *          The timer that fired
  1068.    */
  1069.   notify: function(timer) {
  1070.     // If a download is in progress, then do nothing.
  1071.     if (this.isDownloading || this._downloader && this._downloader.patchIsStaged)
  1072.       return;
  1073.  
  1074.     var self = this;
  1075.     var listener = {
  1076.       /**
  1077.        * See nsIUpdateService.idl
  1078.        */
  1079.       onProgress: function(request, position, totalSize) { 
  1080.       },
  1081.       
  1082.       /**
  1083.        * See nsIUpdateService.idl
  1084.        */
  1085.       onCheckComplete: function(request, updates, updateCount) {
  1086.         self._selectAndInstallUpdate(updates);
  1087.       },
  1088.  
  1089.       /**
  1090.        * See nsIUpdateService.idl
  1091.        */
  1092.       onError: function(request, update) { 
  1093.         LOG("Checker", "Error during background update: " + update.statusText);
  1094.       },
  1095.     }
  1096.     this.backgroundChecker.checkForUpdates(listener, false);
  1097.   },
  1098.   
  1099.   /**
  1100.    * Determine whether or not an update requires user confirmation before it
  1101.    * can be installed.
  1102.    * @param   update
  1103.    *          The update to be installed
  1104.    * @returns true if a prompt UI should be shown asking the user if they want
  1105.    *          to install the update, false if the update should just be 
  1106.    *          silently downloaded and installed.
  1107.    */
  1108.   _shouldPrompt: function(update) {
  1109.     // There are two possible outcomes here:
  1110.     // 1. download and install the update automatically
  1111.     // 2. alert the user about the presence of an update before doing anything
  1112.     //
  1113.     // The outcome we follow is determined as follows:
  1114.     // 
  1115.     // Update Type      Mode      Incompatible    Outcome
  1116.     // Major            0         Yes or No       Auto Install
  1117.     // Major            1         No              Auto Install
  1118.     // Major            1         Yes             Notify and Confirm
  1119.     // Major            2         Yes or No       Notify and Confirm
  1120.     // Minor            0         Yes or No       Auto Install
  1121.     // Minor            1         No              Auto Install
  1122.     // Minor            1         Yes             Notify and Confirm
  1123.     // Minor            2         No              Auto Install
  1124.     // Minor            2         Yes             Notify and Confirm
  1125.     //
  1126.     // In addition, if there is a license associated with an update, regardless
  1127.     // of type it must be agreed to. 
  1128.     //
  1129.     // If app.update.enabled is set to false, an update check is not performed
  1130.     // at all, and so none of the decision making above is entered into.
  1131.     //
  1132.     update.QueryInterface(Components.interfaces.nsIPropertyBag);
  1133.     try {
  1134.       var licenseAccepted = update.getProperty("licenseAccepted") == "true";
  1135.     }
  1136.     catch (e) {
  1137.       licenseAccepted = false;
  1138.     }
  1139.     if (update.licenseURL && !licenseAccepted) {
  1140.       LOG("Checker", "_shouldPrompt: Prompting because of an un-accepted " + 
  1141.           "license");
  1142.       return true;
  1143.     }
  1144.     
  1145.     var updateEnabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true);
  1146.     if (!updateEnabled) {
  1147.       LOG("Checker", "_shouldPrompt: Not prompting because update is " + 
  1148.           "disabled");
  1149.       return false;
  1150.     }
  1151.     
  1152.     // User has turned off automatic download and install
  1153.     var autoEnabled = getPref("getBoolPref", PREF_APP_UPDATE_AUTO, true);
  1154.     if (!autoEnabled) {
  1155.       LOG("Checker", "_shouldPrompt: Prompting because auto install is disabled");
  1156.       return true;
  1157.     }
  1158.     
  1159.     switch (getPref("getIntPref", PREF_APP_UPDATE_MODE, 1)) {
  1160.     case 1:
  1161.       // Mode 1 is do not prompt only if there are no incompatibilities
  1162.       // releases
  1163.       LOG("Checker", "_shouldPrompt: Prompting if there are incompatibilities");
  1164.       return !isCompatible(update);
  1165.     case 2:
  1166.       // Mode 2 is do not prompt only if there are no incompatibilities for 
  1167.       // minor updates only
  1168.       LOG("Checker", "_shouldPrompt: Prompting if major or there are " + 
  1169.           "incompatibilities");
  1170.       return update.type == "minor" ? !isCompatible(update) : true;
  1171.     }
  1172.     // Mode 0 is do not prompt regardless of incompatibilities
  1173.     LOG("Checker", "_shouldPrompt: Not prompting the user - they choose to " +
  1174.         "ignore incompatibilities");
  1175.     return false;
  1176.   },
  1177.   
  1178.   /**
  1179.    * Determine which of the specified updates should be installed.
  1180.    * @param   updates
  1181.    *          An array of available updates
  1182.    */
  1183.   selectUpdate: function(updates) {
  1184.     if (updates.length == 0)
  1185.       return null;
  1186.     
  1187.     // Choose the newest of the available minor and major updates. 
  1188.     var majorUpdate = null, minorUpdate = null;
  1189.     var newestMinor = updates[0], newestMajor = updates[0];
  1190.  
  1191.     var vc = Components.classes["@mozilla.org/xpcom/version-comparator;1"]
  1192.                        .getService(Components.interfaces.nsIVersionComparator);
  1193.     for (var i = 0; i < updates.length; ++i) {
  1194.       if (updates[i].type == "major" && 
  1195.           vc.compare(newestMajor.version, updates[i].version) <= 0)
  1196.         majorUpdate = newestMajor = updates[i];
  1197.       if (updates[i].type == "minor" && 
  1198.           vc.compare(newestMinor.version, updates[i].version) <= 0)
  1199.         minorUpdate = newestMinor = updates[i];
  1200.     }
  1201.  
  1202.     // If there's a major update, always try and fetch that one first, 
  1203.     // otherwise fall back to the newest minor update.
  1204.     return majorUpdate || minorUpdate;
  1205.   },
  1206.   
  1207.   /**
  1208.    * Determine which of the specified updates should be installed and
  1209.    * begin the download/installation process, optionally prompting the
  1210.    * user for permission if required.
  1211.    * @param   updates
  1212.    *          An array of available updates
  1213.    */
  1214.   _selectAndInstallUpdate: function(updates) {
  1215.     // Don't prompt if there's an active update - the user is already 
  1216.     // aware and is downloading, or performed some user action to prevent
  1217.     // notification.
  1218.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  1219.                        .getService(Components.interfaces.nsIUpdateManager);
  1220.     if (um.activeUpdate)
  1221.       return;
  1222.     
  1223.     var update = this.selectUpdate(updates, updates.length);
  1224.     if (!update)
  1225.       return;
  1226.     
  1227.     if (this._shouldPrompt(update))
  1228.       showPromptIfNoIncompatibilities(update);
  1229.     else {
  1230.       LOG("UpdateService", "_selectAndInstallUpdate: No need to show prompt, just download update");
  1231.       var status = this.downloadUpdate(update, true);
  1232.       if (status == STATE_NONE)
  1233.         cleanupActiveUpdate();
  1234.     }
  1235.   },
  1236.  
  1237.   /**
  1238.    * The Checker used for background update checks.
  1239.    */
  1240.   _backgroundChecker: null,
  1241.   
  1242.   /**
  1243.    * See nsIUpdateService.idl
  1244.    */
  1245.   get backgroundChecker() {
  1246.     if (!this._backgroundChecker) 
  1247.       this._backgroundChecker = new Checker();
  1248.     return this._backgroundChecker;
  1249.   },
  1250.   
  1251.   /**
  1252.    * See nsIUpdateService.idl
  1253.    */
  1254.   get canUpdate() {
  1255.     try {
  1256.       var appDirFile = getFile(KEY_APPDIR, [FILE_PERMS_TEST]);
  1257.       if (!appDirFile.exists()) {
  1258.         appDirFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1259.         appDirFile.remove(false);
  1260.       }
  1261.       var updateDir = getUpdatesDir();
  1262.       var upDirFile = updateDir.clone();
  1263.       upDirFile.append(FILE_PERMS_TEST);
  1264.       if (!upDirFile.exists()) {
  1265.         upDirFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1266.         upDirFile.remove(false);
  1267.       }
  1268.     }
  1269.     catch (e) {
  1270.       // No write privileges to install directory
  1271.       return false;
  1272.     }
  1273.     // If the administrator has locked the app update functionality 
  1274.     // OFF - this is not just a user setting, so disable the manual
  1275.     // UI too.
  1276.     var enabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true);
  1277.     if (!enabled && gPref.prefIsLocked(PREF_APP_UPDATE_ENABLED))
  1278.       return false;
  1279.  
  1280.     // If we don't know the binary platform we're updating, we can't update.
  1281.     if (!gABI)
  1282.       return false;
  1283.  
  1284.     return true;
  1285.   },
  1286.   
  1287.   /**
  1288.    * See nsIUpdateService.idl
  1289.    */
  1290.   addDownloadListener: function(listener) {
  1291.     if (!this._downloader) {
  1292.       LOG("UpdateService", "addDownloadListener: no downloader!\n");
  1293.       return;
  1294.     }
  1295.     this._downloader.addDownloadListener(listener);
  1296.   },
  1297.   
  1298.   /**
  1299.    * See nsIUpdateService.idl
  1300.    */
  1301.   removeDownloadListener: function(listener) {
  1302.     if (!this._downloader) {
  1303.       LOG("UpdateService", "removeDownloadListener: no downloader!\n");
  1304.       return;
  1305.     }
  1306.     this._downloader.removeDownloadListener(listener);
  1307.   },
  1308.   
  1309.   /**
  1310.    * See nsIUpdateService.idl
  1311.    */
  1312.   downloadUpdate: function(update, background) {
  1313.     if (!update)
  1314.       throw Components.results.NS_ERROR_NULL_POINTER;
  1315.     if (this.isDownloading) {
  1316.       if (update.isCompleteUpdate == this._downloader.isCompleteUpdate &&
  1317.           background == this._downloader.background) {
  1318.         LOG("UpdateService", "no support for downloading more than one update at a time");
  1319.         return readStatusFile(getUpdatesDir());
  1320.       }
  1321.       this._downloader.cancel();
  1322.     }
  1323.     this._downloader = new Downloader(background);
  1324.     return this._downloader.downloadUpdate(update);
  1325.   },
  1326.   
  1327.   /**
  1328.    * See nsIUpdateService.idl
  1329.    */
  1330.   pauseDownload: function() {
  1331.     if (this.isDownloading)
  1332.       this._downloader.cancel();
  1333.   },
  1334.   
  1335.   /**
  1336.    * See nsIUpdateService.idl
  1337.    */
  1338.   get isDownloading() {
  1339.     return this._downloader && this._downloader.isBusy;
  1340.   },
  1341.   
  1342.   /**
  1343.    * See nsISupports.idl
  1344.    */
  1345.   QueryInterface: function(iid) {
  1346.     if (!iid.equals(Components.interfaces.nsIApplicationUpdateService) &&
  1347.         !iid.equals(Components.interfaces.nsITimerCallback) && 
  1348.         !iid.equals(Components.interfaces.nsIObserver) && 
  1349.         !iid.equals(Components.interfaces.nsISupports))
  1350.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1351.     return this;
  1352.   }
  1353. };
  1354.  
  1355. /**
  1356.  * A service to manage active and past updates.
  1357.  * @constructor
  1358.  */
  1359. function UpdateManager() {
  1360.   // Ensure the Active Update file is loaded
  1361.   var updates = this._loadXMLFileIntoArray(getFile(KEY_APPDIR, 
  1362.     [FILE_UPDATE_ACTIVE]));
  1363.   if (updates.length > 0)
  1364.     this._activeUpdate = updates[0];
  1365. }
  1366. UpdateManager.prototype = {
  1367.   /**
  1368.    * All previously downloaded and installed updates, as an array of nsIUpdate
  1369.    * objects.
  1370.    */
  1371.   _updates: null,
  1372.   
  1373.   /**
  1374.    * The current actively downloading/installing update, as a nsIUpdate object.
  1375.    */
  1376.   _activeUpdate: null,
  1377.   
  1378.   /**
  1379.    * Loads an updates.xml formatted file into an array of nsIUpdate items.
  1380.    * @param   file
  1381.    *          A nsIFile for the updates.xml file
  1382.    * @returns The array of nsIUpdate items held in the file.
  1383.    */
  1384.   _loadXMLFileIntoArray: function(file) {
  1385.     if (!file.exists()) {
  1386.       LOG("UpdateManager", "_loadXMLFileIntoArray: XML File does not exist");
  1387.       return [];
  1388.     }
  1389.  
  1390.     var result = [];
  1391.     var fileStream = Components.classes["@mozilla.org/network/file-input-stream;1"]
  1392.                                .createInstance(Components.interfaces.nsIFileInputStream);
  1393.     fileStream.init(file, MODE_RDONLY, PERMS_FILE, 0);
  1394.     try {
  1395.       var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"]
  1396.                             .createInstance(Components.interfaces.nsIDOMParser);
  1397.       var doc = parser.parseFromStream(fileStream, "UTF-8", fileStream.available(), "text/xml");
  1398.       
  1399.       var updateCount = doc.documentElement.childNodes.length;
  1400.       for (var i = 0; i < updateCount; ++i) {
  1401.         var updateElement = doc.documentElement.childNodes.item(i);
  1402.         if (updateElement.nodeType != Node.ELEMENT_NODE ||
  1403.             updateElement.localName != "update")
  1404.           continue;
  1405.  
  1406.         updateElement.QueryInterface(Components.interfaces.nsIDOMElement);
  1407.         result.push(new Update(updateElement));
  1408.       }
  1409.     }
  1410.     catch (e) {
  1411.       LOG("UpdateManager", "_loadXMLFileIntoArray: Error constructing update list " + 
  1412.           e);
  1413.     }
  1414.     fileStream.close();
  1415.     return result;
  1416.   },
  1417.   
  1418.   /**
  1419.    * Load the update manager, initializing state from state files.
  1420.    */
  1421.   _ensureUpdates: function() {
  1422.     if (!this._updates) {
  1423.       this._updates = this._loadXMLFileIntoArray(getFile(KEY_APPDIR, 
  1424.                         [FILE_UPDATES_DB]));
  1425.  
  1426.       // Make sure that any active update is part of our updates list
  1427.       var active = this.activeUpdate;
  1428.       if (active)
  1429.         this._addUpdate(active);
  1430.     }
  1431.   },
  1432.  
  1433.   /**
  1434.    * See nsIUpdateService.idl
  1435.    */
  1436.   getUpdateAt: function(index) {
  1437.     this._ensureUpdates();
  1438.     return this._updates[index];
  1439.   },
  1440.   
  1441.   /**
  1442.    * See nsIUpdateService.idl
  1443.    */
  1444.   get updateCount() {
  1445.     this._ensureUpdates();
  1446.     return this._updates.length;
  1447.   },
  1448.   
  1449.   /**
  1450.    * See nsIUpdateService.idl
  1451.    */
  1452.   get activeUpdate() {
  1453.     if (this._activeUpdate &&
  1454.         this._activeUpdate.serviceURL != Checker.prototype.updateURL) {
  1455.       // User switched channels, clear out any old active updates and remove
  1456.       // partial downloads
  1457.       this._activeUpdate = null;
  1458.       
  1459.       // Destroy the updates directory, since we're done with it.
  1460.       cleanUpUpdatesDir();
  1461.     }
  1462.     return this._activeUpdate;
  1463.   },
  1464.   set activeUpdate(activeUpdate) {
  1465.     this._addUpdate(activeUpdate);
  1466.     this._activeUpdate = activeUpdate;
  1467.     if (!activeUpdate) {
  1468.       // If |activeUpdate| is null, we have updated both lists - the active list
  1469.       // and the history list, so we want to write both files.
  1470.       this.saveUpdates();
  1471.     }
  1472.     else
  1473.       this._writeUpdatesToXMLFile([this._activeUpdate], 
  1474.                                   getFile(KEY_APPDIR, [FILE_UPDATE_ACTIVE]));
  1475.     return activeUpdate;
  1476.   },
  1477.   
  1478.   /**
  1479.    * Add an update to the Updates list. If the item already exists in the list,
  1480.    * replace the existing value with the new value.
  1481.    * @param   update
  1482.    *          The nsIUpdate object to add.
  1483.    */
  1484.   _addUpdate: function(update) {
  1485.     if (!update)
  1486.       return;
  1487.     if (this._updates) {
  1488.       for (var i = 0; i < this._updates.length; ++i) {
  1489.         if (this._updates[i].version == update.version &&
  1490.             this._updates[i].buildID == update.buildID) {
  1491.           // Replace the existing entry with the new value, updating
  1492.           // all metadata.
  1493.           this._updates[i] = update;
  1494.           return;
  1495.         }
  1496.       }
  1497.     }
  1498.     // Otherwise add it to the front of the list.
  1499.     if (update) 
  1500.       this._updates = [update].concat(this._updates);
  1501.   },
  1502.   
  1503.   /**
  1504.    * Serializes an array of updates to an XML file
  1505.    * @param   updates
  1506.    *          An array of nsIUpdate objects
  1507.    * @param   file
  1508.    *          The nsIFile object to serialize to
  1509.    */
  1510.   _writeUpdatesToXMLFile: function(updates, file) {
  1511.     var fos = Components.classes["@mozilla.org/network/safe-file-output-stream;1"]
  1512.                         .createInstance(Components.interfaces.nsIFileOutputStream);
  1513.     var modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  1514.     if (!file.exists()) 
  1515.       file.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1516.     fos.init(file, modeFlags, PERMS_FILE, 0);
  1517.     
  1518.     try {
  1519.       var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"]
  1520.                             .createInstance(Components.interfaces.nsIDOMParser);
  1521.       const EMPTY_UPDATES_DOCUMENT = "<?xml version=\"1.0\"?><updates xmlns=\"http://www.mozilla.org/2005/app-update\"></updates>";
  1522.       var doc = parser.parseFromString(EMPTY_UPDATES_DOCUMENT, "text/xml");
  1523.  
  1524.       for (var i = 0; i < updates.length; ++i) {
  1525.         if (updates[i])
  1526.           doc.documentElement.appendChild(updates[i].serialize(doc));
  1527.       }
  1528.  
  1529.       var serializer = Components.classes["@mozilla.org/xmlextras/xmlserializer;1"]
  1530.                                 .createInstance(Components.interfaces.nsIDOMSerializer);
  1531.       serializer.serializeToStream(doc.documentElement, fos, null);
  1532.     }
  1533.     catch (e) {
  1534.     }
  1535.     
  1536.     closeSafeOutputStream(fos);
  1537.   },
  1538.  
  1539.   /**
  1540.    * See nsIUpdateService.idl
  1541.    */
  1542.   saveUpdates: function() {
  1543.     this._writeUpdatesToXMLFile([this._activeUpdate], 
  1544.                                 getFile(KEY_APPDIR, [FILE_UPDATE_ACTIVE]));
  1545.     if (this._updates) {
  1546.       this._writeUpdatesToXMLFile(this._updates, 
  1547.                                   getFile(KEY_APPDIR, [FILE_UPDATES_DB]));
  1548.     }
  1549.   },
  1550.   
  1551.   /**
  1552.    * See nsISupports.idl
  1553.    */
  1554.   QueryInterface: function(iid) {
  1555.     if (!iid.equals(Components.interfaces.nsIUpdateManager) &&
  1556.         !iid.equals(Components.interfaces.nsISupports))
  1557.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1558.     return this;
  1559.   }
  1560. };
  1561.  
  1562. /**
  1563.  * This class implements nsIBadCertListener.  It's job is to prevent "bad cert"
  1564.  * security dialogs from being shown to the user.  It is better to simply fail
  1565.  * if the certificate is bad.  See bug 304286.
  1566.  */
  1567. function BadCertHandler() {
  1568. }
  1569. BadCertHandler.prototype = {
  1570.   /**
  1571.    * See nsIBadCertListener
  1572.    */
  1573.   confirmUnknownIssuer: function(socketInfo, cert, certAddType) {
  1574.     return false;
  1575.   },
  1576.  
  1577.   confirmMismatchDomain: function(socketInfo, targetURL, cert) {
  1578.     return false;
  1579.   },
  1580.  
  1581.   confirmCertExpired: function(socketInfo, cert) {
  1582.     return false;
  1583.   },
  1584.  
  1585.   notifyCrlNextupdate: function(socketInfo, targetURL, cert) {
  1586.   },
  1587.  
  1588.   /**
  1589.    * See nsIInterfaceRequestor
  1590.    */
  1591.   getInterface: function(iid) {
  1592.     if (iid.equals(Components.interfaces.nsIBadCertListener))
  1593.       return this;
  1594.  
  1595.     Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE;
  1596.     return null;
  1597.   },
  1598.  
  1599.   /**
  1600.    * See nsISupports
  1601.    */
  1602.   QueryInterface: function(iid) {
  1603.     if (!iid.equals(Components.interfaces.nsIBadCertListener) &&
  1604.         !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
  1605.         !iid.equals(Components.interfaces.nsISupports))
  1606.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1607.     return this;
  1608.   }
  1609. };
  1610.  
  1611. /**
  1612.  * Checker
  1613.  * Checks for new Updates
  1614.  * @constructor
  1615.  */
  1616. function Checker() {
  1617. }
  1618. Checker.prototype = {
  1619.   /**
  1620.    * The XMLHttpRequest object that performs the connection.
  1621.    */
  1622.   _request  : null,
  1623.   
  1624.   /**
  1625.    * The nsIUpdateCheckListener callback
  1626.    */
  1627.   _callback : null,
  1628.   
  1629.   /**
  1630.    * The URL of the update service XML file to connect to that contains details
  1631.    * about available updates.
  1632.    */
  1633.   get updateURL() {
  1634.     var defaults =
  1635.         gPref.QueryInterface(Components.interfaces.nsIPrefService).
  1636.         getDefaultBranch(null);
  1637.  
  1638.     // Use the override URL if specified.
  1639.     var url = getPref("getCharPref", PREF_APP_UPDATE_URL_OVERRIDE, null);
  1640.  
  1641.     // Otherwise, construct the update URL from component parts.
  1642.     if (!url) {
  1643.       try {
  1644.         url = defaults.getCharPref(PREF_APP_UPDATE_URL);
  1645.       } catch (e) {
  1646.       }
  1647.     }
  1648.  
  1649.     if (!url || url == "") {
  1650.       LOG("Checker", "Update URL not defined");
  1651.       return null;
  1652.     }
  1653.  
  1654.     // Read the update channel from defaults only.  We do this to ensure that
  1655.     // the channel is tightly coupled with the application and does not apply
  1656.     // to other instances of the application that may use the same profile.
  1657.     function getUpdateChannel() {
  1658.       try {
  1659.         return defaults.getCharPref(PREF_APP_UPDATE_CHANNEL);
  1660.       } catch (e) {
  1661.         return "default";  // failover when pref not found
  1662.       }
  1663.     }
  1664.  
  1665.     url = url.replace(/%PRODUCT%/g, gApp.name);
  1666.     url = url.replace(/%VERSION%/g, gApp.version);
  1667.     url = url.replace(/%BUILD_ID%/g, gApp.appBuildID);
  1668.     url = url.replace(/%BUILD_TARGET%/g, gApp.OS + "_" + gABI);
  1669.     url = url.replace(/%LOCALE%/g, getLocale());
  1670.     url = url.replace(/%CHANNEL%/g, getUpdateChannel());
  1671.     url = url.replace(/\+/g, "%2B");
  1672.  
  1673.     LOG("Checker", "update url: " + url);
  1674.     return url;
  1675.   },
  1676.   
  1677.   /**
  1678.    * See nsIUpdateService.idl
  1679.    */
  1680.   checkForUpdates: function(listener, force) {
  1681.     if (!listener)
  1682.       throw Components.results.NS_ERROR_NULL_POINTER;
  1683.       
  1684.     if (!this.updateURL || (!this.enabled && !force))
  1685.       return;
  1686.       
  1687.     this._request = 
  1688.       Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].
  1689.       createInstance(Components.interfaces.nsIXMLHttpRequest);
  1690.     this._request.open("GET", this.updateURL, true);
  1691.     this._request.channel.notificationCallbacks = new BadCertHandler();
  1692.     this._request.overrideMimeType("text/xml");
  1693.     this._request.setRequestHeader("Cache-Control", "no-cache");
  1694.     
  1695.     var self = this;
  1696.     this._request.onerror     = function(event) { self.onError(event);    };
  1697.     this._request.onload      = function(event) { self.onLoad(event);     };
  1698.     this._request.onprogress  = function(event) { self.onProgress(event); };
  1699.  
  1700.     LOG("Checker", "checkForUpdates: sending request to " + this.updateURL);
  1701.     this._request.send(null);
  1702.     
  1703.     this._callback = listener;
  1704.   },
  1705.   
  1706.   /**
  1707.    * When progress associated with the XMLHttpRequest is received.
  1708.    * @param   event
  1709.    *          The nsIDOMLSProgressEvent for the load.
  1710.    */
  1711.   onProgress: function(event) {
  1712.     LOG("Checker", "onProgress: " + event.position + "/" + event.totalSize);
  1713.     this._callback.onProgress(event.target, event.position, event.totalSize);
  1714.   },
  1715.   
  1716.   /**
  1717.    * Returns an array of nsIUpdate objects discovered by the update check.
  1718.    */
  1719.   get _updates() {
  1720.     var updatesElement = this._request.responseXML.documentElement;
  1721.     if (!updatesElement) {
  1722.       LOG("Checker", "get_updates: empty updates document?!");
  1723.       return [];
  1724.     }
  1725.  
  1726.     if (updatesElement.nodeName != "updates") {
  1727.       LOG("Checker", "get_updates: unexpected node name!");
  1728.       throw "";
  1729.     }
  1730.     
  1731.     var updates = [];
  1732.     for (var i = 0; i < updatesElement.childNodes.length; ++i) {
  1733.       var updateElement = updatesElement.childNodes.item(i);
  1734.       if (updateElement.nodeType != Node.ELEMENT_NODE ||
  1735.           updateElement.localName != "update")
  1736.         continue;
  1737.  
  1738.       updateElement.QueryInterface(Components.interfaces.nsIDOMElement);
  1739.       var update = new Update(updateElement);
  1740.       update.serviceURL = this.updateURL;
  1741.       updates.push(update);
  1742.     }
  1743.  
  1744.     return updates;
  1745.   },
  1746.   
  1747.   /**
  1748.    * The XMLHttpRequest succeeded and the document was loaded.
  1749.    * @param   event
  1750.    *          The nsIDOMLSEvent for the load
  1751.    */
  1752.   onLoad: function(event) {
  1753.     LOG("Checker", "onLoad: request completed downloading document");
  1754.     
  1755.     // Analyze the resulting DOM and determine the set of updates to install
  1756.     try {
  1757.       var updates = this._updates;
  1758.       
  1759.       LOG("Checker", "Updates available: " + updates.length);
  1760.       
  1761.       // ... and tell the Update Service about what we discovered.
  1762.       this._callback.onCheckComplete(event.target, updates, updates.length);
  1763.     }
  1764.     catch (e) {
  1765.       LOG("Checker", "There was a problem with the update service URL specified, " + 
  1766.           "either the XML file was malformed or it does not exist at the location " + 
  1767.           "specified. Exception: " + e);
  1768.       var update = new Update(null);
  1769.       update.statusText = getStatusTextFromCode(404, 404);
  1770.       this._callback.onError(event.target, update);
  1771.     }
  1772.   },
  1773.   
  1774.   /**
  1775.    * There was an error of some kind during the XMLHttpRequest
  1776.    * @param   event
  1777.    *          The nsIDOMLSEvent for the load
  1778.    */
  1779.   onError: function(event) {
  1780.     LOG("Checker", "onError: error during load");
  1781.     
  1782.     var request = event.target;
  1783.     try {
  1784.       var status = request.status;
  1785.     }
  1786.     catch (e) {
  1787.       var req = request.channel.QueryInterface(Components.interfaces.nsIRequest);
  1788.       status = req.status;
  1789.     }
  1790.     
  1791.     // If we can't find an error string specific to this status code, 
  1792.     // just use the 200 message from above, which means everything 
  1793.     // "looks" fine but there was probably an XML error or a bogus file.
  1794.     var update = new Update(null);
  1795.     update.statusText = getStatusTextFromCode(status, 200);
  1796.     this._callback.onError(request, update);
  1797.   },
  1798.   
  1799.   /**
  1800.    * Whether or not we are allowed to do update checking.
  1801.    */
  1802.   _enabled: true,
  1803.   
  1804.   /**
  1805.    * See nsIUpdateService.idl
  1806.    */
  1807.   get enabled() {
  1808.     var aus = 
  1809.         Components.classes["@mozilla.org/updates/update-service;1"].
  1810.         getService(Components.interfaces.nsIApplicationUpdateService);
  1811.     var enabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true) && 
  1812.                   aus.canUpdate && this._enabled;
  1813.     return enabled;
  1814.   },
  1815.   
  1816.   /**
  1817.    * See nsIUpdateService.idl
  1818.    */
  1819.   stopChecking: function(duration) {
  1820.     // Always stop the current check
  1821.     if (this._request)
  1822.       this._request.abort();
  1823.     
  1824.     const nsIUpdateChecker = Components.interfaces.nsIUpdateChecker;
  1825.     switch (duration) {
  1826.     case nsIUpdateChecker.CURRENT_SESSION:
  1827.       this._enabled = false;
  1828.       break;
  1829.     case nsIUpdateChecker.ANY_CHECKS:
  1830.       this._enabled = false;
  1831.       gPref.setBoolPref(PREF_APP_UPDATE_ENABLED, this._enabled);
  1832.       break;
  1833.     }
  1834.   },
  1835.   
  1836.   /**
  1837.    * See nsISupports.idl
  1838.    */
  1839.   QueryInterface: function(iid) {
  1840.     if (!iid.equals(Components.interfaces.nsIUpdateChecker) &&
  1841.         !iid.equals(Components.interfaces.nsISupports))
  1842.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1843.     return this;
  1844.   }
  1845. };
  1846.  
  1847. /**
  1848.  * Manages the download of updates
  1849.  * @param   background
  1850.  *          Whether or not this downloader is operating in background
  1851.  *          update mode. 
  1852.  * @constructor
  1853.  */
  1854. function Downloader(background) {
  1855.   this.background = background;
  1856. }
  1857. Downloader.prototype = {
  1858.   /**
  1859.    * The nsIUpdatePatch that we are downloading
  1860.    */
  1861.   _patch: null,
  1862.   
  1863.   /**
  1864.    * The nsIUpdate that we are downloading
  1865.    */
  1866.   _update: null,
  1867.   
  1868.   /**
  1869.    * The nsIIncrementalDownload object handling the download
  1870.    */
  1871.   _request: null,
  1872.  
  1873.   /**
  1874.    * Whether or not the update being downloaded is a complete replacement of
  1875.    * the user's existing installation or a patch representing the difference
  1876.    * between the new version and the previous version.
  1877.    */
  1878.   isCompleteUpdate: null,
  1879.  
  1880.   /**
  1881.    * Cancels the active download.
  1882.    */  
  1883.   cancel: function() {
  1884.     if (this._request && 
  1885.         this._request instanceof Components.interfaces.nsIRequest) {
  1886.       const NS_BINDING_ABORTED = 0x804b0002;
  1887.       this._request.cancel(NS_BINDING_ABORTED);
  1888.     }
  1889.   },
  1890.  
  1891.   /**
  1892.    * Whether or not a patch has been downloaded and staged for installation.
  1893.    */
  1894.   get patchIsStaged() {
  1895.     return readStatusFile(getUpdatesDir()) == STATE_PENDING;
  1896.   },
  1897.  
  1898.   /**
  1899.    * Verify the downloaded file.  We assume that the download is complete at
  1900.    * this point.
  1901.    */
  1902.   _verifyDownload: function() {
  1903.     if (!this._request)
  1904.       return false;
  1905.  
  1906.     var destination = this._request.destination;
  1907.  
  1908.     // Ensure that the file size matches the expected file size.
  1909.     if (destination.fileSize != this._patch.size)
  1910.       return false;
  1911.  
  1912.     var fileStream = Components.classes["@mozilla.org/network/file-input-stream;1"].
  1913.         createInstance(nsIFileInputStream);
  1914.     fileStream.init(destination, MODE_RDONLY, PERMS_FILE, 0);
  1915.  
  1916.     try {
  1917.       var hash = Components.classes["@mozilla.org/security/hash;1"].
  1918.           createInstance(nsICryptoHash);
  1919.       var hashFunction = nsICryptoHash[this._patch.hashFunction.toUpperCase()];
  1920.       if (hashFunction == undefined)
  1921.         throw Components.results.NS_ERROR_UNEXPECTED;
  1922.       hash.init(hashFunction);
  1923.       hash.updateFromStream(fileStream, -1);
  1924.       // NOTE: For now, we assume that the format of _patch.hashValue is hex
  1925.       // encoded binary (such as what is typically output by programs like
  1926.       // sha1sum).  In the future, this may change to base64 depending on how
  1927.       // we choose to compute these hashes.
  1928.       digest = binaryToHex(hash.finish(false));
  1929.     } catch (e) {
  1930.       LOG("Downloader", "failed to compute hash of downloaded update archive");
  1931.       digest = "";
  1932.     }
  1933.  
  1934.     fileStream.close();
  1935.  
  1936.     return digest == this._patch.hashValue.toLowerCase();
  1937.   },
  1938.  
  1939.   /**
  1940.    * Select the patch to use given the current state of updateDir and the given
  1941.    * set of update patches.
  1942.    * @param   update
  1943.    *          A nsIUpdate object to select a patch from
  1944.    * @param   updateDir
  1945.    *          A nsIFile representing the update directory
  1946.    * @returns A nsIUpdatePatch object to download
  1947.    */
  1948.   _selectPatch: function(update, updateDir) {
  1949.     // Given an update to download, we will always try to download the patch
  1950.     // for a partial update over the patch for a full update.
  1951.  
  1952.     /**
  1953.      * Return the first UpdatePatch with the given type.
  1954.      * @param   type
  1955.      *          The type of the patch ("complete" or "partial")
  1956.      * @returns A nsIUpdatePatch object matching the type specified
  1957.      */
  1958.     function getPatchOfType(type) {
  1959.       for (var i = 0; i < update.patchCount; ++i) {
  1960.         var patch = update.getPatchAt(i);
  1961.         if (patch && patch.type == type)
  1962.           return patch;
  1963.       }
  1964.       return null;
  1965.     }
  1966.  
  1967.     // Look to see if any of the patches in the Update object has been
  1968.     // pre-selected for download, otherwise we must figure out which one
  1969.     // to select ourselves. 
  1970.     var selectedPatch = update.selectedPatch;
  1971.     
  1972.     var state = readStatusFile(updateDir)
  1973.  
  1974.     // If this is a patch that we know about, then select it.  If it is a patch
  1975.     // that we do not know about, then remove it and use our default logic.
  1976.     var useComplete = false;
  1977.     if (selectedPatch) {
  1978.       LOG("Downloader", "found existing patch [state="+state+"]");
  1979.       switch (state) {
  1980.       case STATE_DOWNLOADING: 
  1981.         LOG("Downloader", "resuming download");
  1982.         return selectedPatch;
  1983.       case STATE_PENDING:
  1984.         LOG("Downloader", "already downloaded and staged");
  1985.         return null;
  1986.       default:
  1987.         // Something went wrong when we tried to apply the previous patch.
  1988.         // Try the complete patch next time.
  1989.         if (update && selectedPatch.type == "partial") {
  1990.           useComplete = true;
  1991.         } else {
  1992.           // This is a pretty fatal error.  Just bail.
  1993.           LOG("Downloader", "failed to apply complete patch!");
  1994.           writeStatusFile(updateDir, STATE_NONE);
  1995.           return null;
  1996.         }
  1997.       }
  1998.  
  1999.       selectedPatch = null;
  2000.     }
  2001.     
  2002.     // If we were not able to discover an update from a previous download, we 
  2003.     // select the best patch from the given set.
  2004.     var partialPatch = getPatchOfType("partial");
  2005.     if (!useComplete)
  2006.       selectedPatch = partialPatch;
  2007.     if (!selectedPatch) {
  2008.       if (partialPatch)
  2009.         partialPatch.selected = false;
  2010.       selectedPatch = getPatchOfType("complete");
  2011.     }
  2012.  
  2013.     // Restore the updateDir since we may have deleted it.
  2014.     updateDir = getUpdatesDir();
  2015.     
  2016.     selectedPatch.selected = true;
  2017.     update.isCompleteUpdate = useComplete;
  2018.     
  2019.     // Reset the Active Update object on the Update Manager and flush the
  2020.     // Active Update DB. 
  2021.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  2022.                        .getService(Components.interfaces.nsIUpdateManager);
  2023.     um.activeUpdate = update;
  2024.  
  2025.     return selectedPatch;
  2026.   },
  2027.  
  2028.   /**
  2029.    * Whether or not we are currently downloading something.
  2030.    */
  2031.   get isBusy() {
  2032.     return this._request != null;
  2033.   },
  2034.   
  2035.   /**
  2036.    * Download and stage the given update.
  2037.    * @param   update
  2038.    *          A nsIUpdate object to download a patch for. Cannot be null.
  2039.    */
  2040.   downloadUpdate: function(update) {
  2041.     if (!update)
  2042.       throw Components.results.NS_ERROR_NULL_POINTER;
  2043.     
  2044.     var updateDir = getUpdatesDir();
  2045.  
  2046.     this._update = update;
  2047.  
  2048.     // This function may return null, which indicates that there are no patches
  2049.     // to download.
  2050.     this._patch = this._selectPatch(update, updateDir);
  2051.     if (!this._patch) {
  2052.       LOG("Downloader", "no patch to download");
  2053.       return readStatusFile(updateDir);
  2054.     }
  2055.     this.isCompleteUpdate = this._patch.type == "complete";
  2056.  
  2057.     var patchFile = updateDir.clone();
  2058.     patchFile.append(FILE_UPDATE_ARCHIVE);
  2059.  
  2060.     var ios = Components.classes["@mozilla.org/network/io-service;1"].
  2061.         getService(Components.interfaces.nsIIOService);
  2062.     var uri = ios.newURI(this._patch.URL, null, null);
  2063.  
  2064.     this._request =
  2065.         Components.classes["@mozilla.org/network/incremental-download;1"].
  2066.         createInstance(nsIIncrementalDownload);
  2067.  
  2068.     LOG("Downloader", "downloadUpdate: Downloading from " + uri.spec + " to " + 
  2069.         patchFile.path);
  2070.  
  2071.     var interval = this.background ? DOWNLOAD_BACKGROUND_INTERVAL
  2072.                                    : DOWNLOAD_FOREGROUND_INTERVAL;
  2073.     this._request.init(uri, patchFile, DOWNLOAD_CHUNK_SIZE, interval);
  2074.     this._request.start(this, null);
  2075.  
  2076.     writeStatusFile(updateDir, STATE_DOWNLOADING);
  2077.     this._patch.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  2078.     this._patch.state = STATE_DOWNLOADING;
  2079.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  2080.                        .getService(Components.interfaces.nsIUpdateManager);
  2081.     um.saveUpdates();
  2082.     return STATE_DOWNLOADING;
  2083.   },
  2084.   
  2085.   /**
  2086.    * An array of download listeners to notify when we receive 
  2087.    * nsIRequestObserver or nsIProgressEventSink method calls.
  2088.    */
  2089.   _listeners: [],
  2090.  
  2091.   /** 
  2092.    * Adds a listener to the download process
  2093.    * @param   listener
  2094.    *          A download listener, implementing nsIRequestObserver and
  2095.    *          nsIProgressEventSink
  2096.    */
  2097.   addDownloadListener: function(listener) {
  2098.     for (var i = 0; i < this._listeners.length; ++i) {
  2099.       if (this._listeners[i] == listener)
  2100.         return;
  2101.     }
  2102.     this._listeners.push(listener);
  2103.   },
  2104.   
  2105.   /** 
  2106.    * Removes a download listener
  2107.    * @param   listener
  2108.    *          The listener to remove.
  2109.    */
  2110.   removeDownloadListener: function(listener) {
  2111.     for (var i = 0; i < this._listeners.length; ++i) {
  2112.       if (this._listeners[i] == listener) {
  2113.         this._listeners.splice(i, 1);
  2114.         return;
  2115.       }
  2116.     }
  2117.   },
  2118.   
  2119.   /**
  2120.    * When the async request begins
  2121.    * @param   request
  2122.    *          The nsIRequest object for the transfer
  2123.    * @param   context
  2124.    *          Additional data
  2125.    */
  2126.   onStartRequest: function(request, context) {
  2127.     request.QueryInterface(nsIIncrementalDownload);
  2128.     LOG("Downloader", "onStartRequest: " + request.URI.spec);
  2129.     
  2130.     var listenerCount = this._listeners.length;
  2131.     for (var i = 0; i < listenerCount; ++i)
  2132.       this._listeners[i].onStartRequest(request, context);
  2133.   },
  2134.   
  2135.   /** 
  2136.    * When new data has been downloaded
  2137.    * @param   request
  2138.    *          The nsIRequest object for the transfer
  2139.    * @param   context
  2140.    *          Additional data
  2141.    * @param   progress
  2142.    *          The current number of bytes transferred
  2143.    * @param   maxProgress
  2144.    *          The total number of bytes that must be transferred
  2145.    */
  2146.   onProgress: function(request, context, progress, maxProgress) {
  2147.     request.QueryInterface(nsIIncrementalDownload);
  2148.     LOG("Downloader.onProgress", "onProgress: " + request.URI.spec + ", " + progress + "/" + maxProgress);
  2149.     
  2150.     var listenerCount = this._listeners.length;
  2151.     for (var i = 0; i < listenerCount; ++i) {
  2152.       var listener = this._listeners[i];
  2153.       if (listener instanceof Components.interfaces.nsIProgressEventSink)
  2154.         listener.onProgress(request, context, progress, maxProgress);
  2155.     }
  2156.   },
  2157.   
  2158.   /** 
  2159.    * When we have new status text
  2160.    * @param   request
  2161.    *          The nsIRequest object for the transfer
  2162.    * @param   context
  2163.    *          Additional data
  2164.    * @param   status
  2165.    *          A status code
  2166.    * @param   statusText
  2167.    *          Human readable version of |status|
  2168.    */
  2169.   onStatus: function(request, context, status, statusText) {
  2170.     request.QueryInterface(nsIIncrementalDownload);
  2171.     LOG("Downloader", "onStatus: " + request.URI.spec + " status = " + status + ", text = " + statusText);
  2172.     var listenerCount = this._listeners.length;
  2173.     for (var i = 0; i < listenerCount; ++i) {
  2174.       var listener = this._listeners[i];
  2175.       if (listener instanceof Components.interfaces.nsIProgressEventSink)
  2176.         listener.onStatus(request, context, status, statusText);
  2177.     }
  2178.   },
  2179.   
  2180.   /** 
  2181.    * When data transfer ceases
  2182.    * @param   request
  2183.    *          The nsIRequest object for the transfer
  2184.    * @param   context
  2185.    *          Additional data
  2186.    * @param   status
  2187.    *          Status code containing the reason for the cessation.
  2188.    */
  2189.   onStopRequest: function(request, context, status) {
  2190.     request.QueryInterface(nsIIncrementalDownload);
  2191.     LOG("Downloader", "onStopRequest: " + request.URI.spec + ", status = " + status);
  2192.  
  2193.     var state = this._patch.state;
  2194.     var shouldShowPrompt = false;
  2195.     var deleteActiveUpdate = false;
  2196.     const NS_BINDING_ABORTED = 0x804b0002;
  2197.     const NS_ERROR_ABORT = 0x80004004;
  2198.     if (Components.isSuccessCode(status)) {
  2199.       if (this._verifyDownload()) {
  2200.         state = STATE_PENDING;
  2201.         
  2202.         // We only need to explicitly show the prompt if this is a backround
  2203.         // download, since otherwise some kind of UI is already visible and 
  2204.         // that UI will notify. 
  2205.         if (this.background)
  2206.           shouldShowPrompt = true;
  2207.         
  2208.         // Tell the updater.exe we're ready to apply.
  2209.         writeStatusFile(getUpdatesDir(), state);
  2210.         this._update.installDate = (new Date()).getTime();
  2211.         this._update.statusText = "Install Pending";
  2212.       } else {
  2213.         LOG("Downloader", "onStopRequest: download verification failed");
  2214.         state = STATE_DOWNLOAD_FAILED;
  2215.         
  2216.         var sbs = 
  2217.             Components.classes["@mozilla.org/intl/stringbundle;1"].
  2218.             getService(Components.interfaces.nsIStringBundleService);
  2219.         var updateStrings = sbs.createBundle(URI_UPDATES_PROPERTIES);
  2220.         var brandStrings = sbs.createBundle(URI_BRAND_PROPERTIES);
  2221.         var brandShortName = brandStrings.GetStringFromName("brandShortName");
  2222.         this._update.statusText = updateStrings.
  2223.           formatStringFromName("verificationError", [brandShortName], 1);
  2224.         
  2225.         // TODO: use more informative error code here
  2226.         status = Components.results.NS_ERROR_UNEXPECTED;
  2227.         
  2228.         var message = getStatusTextFromCode("verification_failed", 
  2229.           "verification_failed");
  2230.         this._update.statusText = message;
  2231.         
  2232.         if (this._update.isCompleteUpdate)
  2233.           deleteActiveUpdate = true;
  2234.  
  2235.         // Destroy the updates directory, since we're done with it.
  2236.         cleanUpUpdatesDir();
  2237.       }
  2238.     }
  2239.     else if (status != NS_BINDING_ABORTED &&
  2240.              status != NS_ERROR_ABORT) {
  2241.       LOG("Downloader", "onStopRequest: Non-verification failure");
  2242.       // Some sort of other failure, log this in the |statusText| property
  2243.       state = STATE_DOWNLOAD_FAILED;
  2244.       
  2245.       // XXXben - if |request| (The Incremental Download) provided a means
  2246.       // for accessing the http channel we could do more here.
  2247.       
  2248.       const NS_BINDING_FAILED = 2152398849;
  2249.       this._update.statusText = getStatusTextFromCode(status, 
  2250.         NS_BINDING_FAILED);
  2251.       
  2252.       // Destroy the updates directory, since we're done with it.
  2253.       cleanUpUpdatesDir();
  2254.       
  2255.       deleteActiveUpdate = true;
  2256.     }
  2257.     LOG("Downloader", "Setting state to: " + state);
  2258.     this._patch.state = state;
  2259.     var um = 
  2260.         Components.classes["@mozilla.org/updates/update-manager;1"].
  2261.         getService(Components.interfaces.nsIUpdateManager);
  2262.     if (deleteActiveUpdate) {
  2263.       this._update.installDate = (new Date()).getTime();
  2264.       um.activeUpdate = null;
  2265.     }
  2266.     um.saveUpdates();
  2267.     
  2268.     var listenerCount = this._listeners.length;
  2269.     for (var i = 0; i < listenerCount; ++i)
  2270.       this._listeners[i].onStopRequest(request, context, status);
  2271.  
  2272.     this._request = null;
  2273.     
  2274.     if (state == STATE_DOWNLOAD_FAILED) {
  2275.       if (!this._update.isCompleteUpdate) {
  2276.         // If we were downloading a patch and the patch verification phase 
  2277.         // failed, log this and then commence downloading the complete update.
  2278.         LOG("Downloader", "onStopRequest: Verification of patch failed, downloading complete update");
  2279.         this._update.isCompleteUpdate = true;
  2280.         var status = this.downloadUpdate(this._update);
  2281.         if (status == STATE_NONE)
  2282.           cleanupActiveUpdate();
  2283.         // This will reset the |.state| property on this._update if a new 
  2284.         // download initiates.
  2285.       }
  2286.       else {
  2287.         // In all other failure cases, i.e. we're S.O.L. - no more failing over
  2288.         // ...
  2289.         
  2290.         // If this was ever a foreground download, and now there is no UI active
  2291.         // (e.g. because the user closed the download window) and there was an
  2292.         // error, we must notify now. Otherwise we can keep the failure to 
  2293.         // ourselves since the user won't be expecting it. 
  2294.         var fgdl = false;
  2295.         try {
  2296.           fgdl = this._update.getProperty("foregroundDownload");
  2297.         }
  2298.         catch (e) {
  2299.         }
  2300.         if (fgdl == "true") {
  2301.           var prompter = 
  2302.               Components.classes["@mozilla.org/updates/update-prompt;1"].
  2303.               createInstance(Components.interfaces.nsIUpdatePrompt);
  2304.           this._update.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  2305.           this._update.setProperty("downloadFailed", "true");
  2306.           prompter.showUpdateError(this._update);
  2307.         }
  2308.       }
  2309.     }
  2310.  
  2311.     // Do this after *everything* else, since it will likely cause the app 
  2312.     // to shut down. 
  2313.     if (shouldShowPrompt) {
  2314.       // Notify the user that an update has been downloaded and is ready for 
  2315.       // installation (i.e. that they should restart the application). We do
  2316.       // not notify on failed update attempts.
  2317.       var prompter = 
  2318.           Components.classes["@mozilla.org/updates/update-prompt;1"].
  2319.           createInstance(Components.interfaces.nsIUpdatePrompt);
  2320.       prompter.showUpdateDownloaded(this._update);
  2321.     }
  2322.   },
  2323.  
  2324.   /**
  2325.    * See nsIInterfaceRequestor.idl
  2326.    */
  2327.   getInterface: function(iid) {
  2328.     // The network request may require proxy authentication, so provide the
  2329.     // default nsIAuthPrompt if requested.
  2330.     if (iid.equals(Components.interfaces.nsIAuthPrompt)) {
  2331.       var prompt =
  2332.           Components.classes["@mozilla.org/network/default-auth-prompt;1"].
  2333.           createInstance();
  2334.       return prompt.QueryInterface(iid);
  2335.     }
  2336.     Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE;
  2337.     return null;
  2338.   },
  2339.    
  2340.   /**
  2341.    * See nsISupports.idl
  2342.    */
  2343.   QueryInterface: function(iid) {
  2344.     if (!iid.equals(Components.interfaces.nsIRequestObserver) &&
  2345.         !iid.equals(Components.interfaces.nsIProgressEventSink) &&
  2346.         !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
  2347.         !iid.equals(Components.interfaces.nsISupports))
  2348.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2349.     return this;
  2350.   }
  2351. };
  2352.  
  2353. /**
  2354.  * A manager for update check timers. Manages timers that fire over long 
  2355.  * periods of time (e.g. days, weeks).
  2356.  * @constructor
  2357.  */
  2358. function TimerManager() {
  2359.   gOS = Components.classes["@mozilla.org/observer-service;1"]
  2360.                   .getService(Components.interfaces.nsIObserverService);
  2361.   gOS.addObserver(this, "xpcom-shutdown", false);
  2362.  
  2363.   const nsITimer = Components.interfaces.nsITimer;
  2364.   this._timer = Components.classes["@mozilla.org/timer;1"]
  2365.                           .createInstance(nsITimer);
  2366.   var timerInterval = getPref("getIntPref", PREF_APP_UPDATE_TIMER, 600000);
  2367.   this._timer.initWithCallback(this, timerInterval, 
  2368.                                nsITimer.TYPE_REPEATING_SLACK);
  2369. }
  2370. TimerManager.prototype = {
  2371.   /**
  2372.    * See nsIObserver.idl
  2373.    */
  2374.   observe: function(subject, topic, data) {
  2375.     if (topic == "xpcom-shutdown") {
  2376.       gOS.removeObserver(this, "xpcom-shutdown");
  2377.  
  2378.       // Release everything we hold onto. 
  2379.       this._timer = null;
  2380.       this._timers = null;
  2381.     }
  2382.   },
  2383.  
  2384.   /**
  2385.    * The Checker Timer
  2386.    */
  2387.   _timer: null,
  2388.   
  2389.   /**
  2390.    * The set of registered timers.
  2391.    */
  2392.   _timers: { },
  2393.   
  2394.   /**
  2395.    * Called when the checking timer fires.
  2396.    * @param   timer
  2397.    *          The checking timer that fired. 
  2398.    */
  2399.   notify: function(timer) {
  2400.     for (var timerID in this._timers) {
  2401.       var timerData = this._timers[timerID];
  2402.       var lastUpdateTime = timerData.lastUpdateTime;
  2403.       var now = Math.round(Date.now() / 1000);
  2404.     
  2405.       // Fudge the lastUpdateTime by some random increment of the update 
  2406.       // check interval (e.g. some random slice of 10 minutes) so that when
  2407.       // the time comes to check, we offset each client request by a random
  2408.       // amount so they don't all hit at once. app.update.timer is in milliseconds,
  2409.       // whereas app.update.lastUpdateTime is in seconds
  2410.       var timerInterval = getPref("getIntPref", PREF_APP_UPDATE_TIMER, 600000);
  2411.       lastUpdateTime += Math.round(Math.random() * timerInterval / 1000);
  2412.  
  2413.       if ((now - lastUpdateTime) > timerData.interval &&
  2414.           timerData.callback instanceof Components.interfaces.nsITimerCallback) {
  2415.         timerData.callback.notify(timer);
  2416.         timerData.lastUpdateTime = now;
  2417.         var preference = PREF_APP_UPDATE_LASTUPDATETIME_FMT.replace(/%ID%/, timerID);
  2418.         gPref.setIntPref(preference, now);
  2419.       }
  2420.     }
  2421.   },
  2422.   
  2423.   /**
  2424.    * See nsIUpdateService.idl
  2425.    */
  2426.   registerTimer: function(id, callback, interval) {
  2427.     var preference = PREF_APP_UPDATE_LASTUPDATETIME_FMT.replace(/%ID%/, id);
  2428.     var now = Math.round(Date.now() / 1000);
  2429.     var lastUpdateTime = null;
  2430.     if (gPref.prefHasUserValue(preference)) {
  2431.       lastUpdateTime = gPref.getIntPref(preference);
  2432.     } else {
  2433.       gPref.setIntPref(preference, now);
  2434.       lastUpdateTime = now;
  2435.     }
  2436.     this._timers[id] = { callback       : callback, 
  2437.                          interval       : interval,
  2438.                          lastUpdateTime : lastUpdateTime }; 
  2439.   },
  2440.  
  2441.   /**
  2442.    * See nsISupports.idl
  2443.    */
  2444.   QueryInterface: function(iid) {
  2445.     if (!iid.equals(Components.interfaces.nsIUpdateTimerManager) &&
  2446.         !iid.equals(Components.interfaces.nsITimerCallback) &&
  2447.         !iid.equals(Components.interfaces.nsIObserver) &&
  2448.         !iid.equals(Components.interfaces.nsISupports))
  2449.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2450.     return this;
  2451.   }
  2452. };
  2453.  
  2454. //@line 2502 "/var/tmp/portage/mozilla-firefox-1.5.0.3/work/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2455. /**
  2456.  * UpdatePrompt
  2457.  * An object which can prompt the user with information about updates, request
  2458.  * action, etc. Embedding clients can override this component with one that 
  2459.  * invokes a native front end. 
  2460.  * @constructor
  2461.  */
  2462. function UpdatePrompt() {
  2463. }
  2464. UpdatePrompt.prototype = {
  2465.   /**
  2466.    * See nsIUpdateService.idl
  2467.    */
  2468.   checkForUpdates: function() {
  2469.     this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2470.                  null, null);
  2471.   },
  2472.     
  2473.   /**
  2474.    * See nsIUpdateService.idl
  2475.    */
  2476.   showUpdateAvailable: function(update) {
  2477.     if (this._enabled) {
  2478.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2479.                    "updatesavailable", update);
  2480.     }
  2481.   },
  2482.   
  2483.   /**
  2484.    * See nsIUpdateService.idl
  2485.    */
  2486.   showUpdateDownloaded: function(update) {
  2487.     if (this._enabled) {
  2488.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2489.                    "finishedBackground", update);
  2490.     }
  2491.   },
  2492.   
  2493.   /**
  2494.    * See nsIUpdateService.idl
  2495.    */
  2496.   showUpdateInstalled: function(update) {
  2497.     var showUpdateInstalledUI = getPref("getBoolPref", 
  2498.       PREF_APP_UPDATE_SHOW_INSTALLED_UI, true);
  2499.     if (this._enabled && showUpdateInstalledUI) {
  2500.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2501.                    "installed", update);
  2502.     }
  2503.   },
  2504.   
  2505.   /**
  2506.    * See nsIUpdateService.idl
  2507.    */
  2508.   showUpdateError: function(update) {
  2509.     if (this._enabled) {
  2510.       // In some cases, we want to just show a simple alert dialog:
  2511.       if (update.state == STATE_FAILED && update.errorCode == WRITE_ERROR) {
  2512.         var sbs = 
  2513.             Components.classes["@mozilla.org/intl/stringbundle;1"].
  2514.             getService(Components.interfaces.nsIStringBundleService);
  2515.         var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  2516.         var title = updateBundle.GetStringFromName("updaterIOErrorTitle");
  2517.         var text = updateBundle.formatStringFromName("updaterIOErrorText",
  2518.                                                      [gApp.name], 1);
  2519.         var ww =
  2520.             Components.classes["@mozilla.org/embedcomp/window-watcher;1"].
  2521.             getService(Components.interfaces.nsIWindowWatcher);
  2522.         ww.getNewPrompter(null).alert(title, text);
  2523.       } else {
  2524.         this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2525.                      "errors", update);
  2526.       }
  2527.     }
  2528.   },
  2529.   
  2530.   /**
  2531.    * See nsIUpdateService.idl
  2532.    */
  2533.   showUpdateHistory: function(parent) {
  2534.     this._showUI(parent, URI_UPDATE_HISTORY_DIALOG, "modal,dialog=yes", "Update:History", 
  2535.                  null, null);
  2536.   },
  2537.   
  2538.   /**
  2539.    * Whether or not we are enabled (i.e. not in Silent mode)
  2540.    */
  2541.   get _enabled() {
  2542.     return !getPref("getBoolPref", PREF_APP_UPDATE_SILENT, false);
  2543.   },
  2544.   
  2545.   /**
  2546.    * Show the Update Checking UI
  2547.    * @param   parent
  2548.    *          A parent window, can be null
  2549.    * @param   uri
  2550.    *          The URI string of the dialog to show
  2551.    * @param   name
  2552.    *          The Window Name of the dialog to show, in case it is already open
  2553.    *          and can merely be focused
  2554.    * @param   page
  2555.    *          The page of the wizard to be displayed, if one is already open.
  2556.    * @param   update
  2557.    *          An update to pass to the UI in the window arguments. 
  2558.    *          Can be null
  2559.    */
  2560.   _showUI: function(parent, uri, features, name, page, update) {
  2561.     var ary = null;
  2562.     if (update) {
  2563.       ary = Components.classes["@mozilla.org/supports-array;1"]
  2564.                       .createInstance(Components.interfaces.nsISupportsArray);
  2565.       ary.AppendElement(update);
  2566.     }
  2567.       
  2568.     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  2569.                        .getService(Components.interfaces.nsIWindowMediator);
  2570.     var win = wm.getMostRecentWindow(name);
  2571.     if (win) {
  2572.       if (page && "setCurrentPage" in win)
  2573.         win.setCurrentPage(page);
  2574.       win.focus();
  2575.     }
  2576.     else {
  2577.       var openFeatures = "chrome,centerscreen,dialog=no,resizable=no,titlebar,toolbar=no";
  2578.       if (features)
  2579.         openFeatures += "," + features;
  2580.       var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  2581.                          .getService(Components.interfaces.nsIWindowWatcher);
  2582.       ww.openWindow(parent, uri, "", openFeatures, ary);
  2583.     }
  2584.   },
  2585.   
  2586.   /**
  2587.    * See nsISupports.idl
  2588.    */
  2589.   QueryInterface: function(iid) {
  2590.     if (!iid.equals(Components.interfaces.nsIUpdatePrompt) &&
  2591.         !iid.equals(Components.interfaces.nsISupports))
  2592.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2593.     return this;
  2594.   }
  2595. };
  2596. //@line 2644 "/var/tmp/portage/mozilla-firefox-1.5.0.3/work/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2597.  
  2598. var gModule = {
  2599.   registerSelf: function(componentManager, fileSpec, location, type) {
  2600.     componentManager = componentManager.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  2601.     
  2602.     for (var key in this._objects) {
  2603.       var obj = this._objects[key];
  2604.       componentManager.registerFactoryLocation(obj.CID, obj.className, obj.contractID,
  2605.                                                fileSpec, location, type);
  2606.     }
  2607.  
  2608.     // Make the Update Service a startup observer
  2609.     var categoryManager = Components.classes["@mozilla.org/categorymanager;1"]
  2610.                                     .getService(Components.interfaces.nsICategoryManager);
  2611.     categoryManager.addCategoryEntry("app-startup", this._objects.service.className,
  2612.                                      "service," + this._objects.service.contractID, 
  2613.                                      true, true, null);
  2614.   },
  2615.   
  2616.   getClassObject: function(componentManager, cid, iid) {
  2617.     if (!iid.equals(Components.interfaces.nsIFactory))
  2618.       throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  2619.  
  2620.     for (var key in this._objects) {
  2621.       if (cid.equals(this._objects[key].CID))
  2622.         return this._objects[key].factory;
  2623.     }
  2624.     
  2625.     throw Components.results.NS_ERROR_NO_INTERFACE;
  2626.   },
  2627.   
  2628.   _makeFactory: #1= function(ctor) {
  2629.     function ci(outer, iid) {
  2630.       if (outer != null)
  2631.         throw Components.results.NS_ERROR_NO_AGGREGATION;
  2632.       return (new ctor()).QueryInterface(iid);
  2633.     } 
  2634.     return { createInstance: ci };
  2635.   },
  2636.   
  2637.   _objects: {
  2638.     service: { CID        : Components.ID("{B3C290A6-3943-4B89-8BBE-C01EB7B3B311}"),
  2639.                contractID : "@mozilla.org/updates/update-service;1",
  2640.                className  : "Update Service",
  2641.                factory    : #1#(UpdateService)
  2642.              },
  2643.     checker: { CID        : Components.ID("{898CDC9B-E43F-422F-9CC4-2F6291B415A3}"),
  2644.                contractID : "@mozilla.org/updates/update-checker;1",
  2645.                className  : "Update Checker",
  2646.                factory    : #1#(Checker)
  2647.              },
  2648. //@line 2696 "/var/tmp/portage/mozilla-firefox-1.5.0.3/work/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2649.     prompt:  { CID        : Components.ID("{27ABA825-35B5-4018-9FDD-F99250A0E722}"),
  2650.                contractID : "@mozilla.org/updates/update-prompt;1",
  2651.                className  : "Update Prompt",
  2652.                factory    : #1#(UpdatePrompt)
  2653.              },
  2654. //@line 2702 "/var/tmp/portage/mozilla-firefox-1.5.0.3/work/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2655.     timers:  { CID        : Components.ID("{B322A5C0-A419-484E-96BA-D7182163899F}"),
  2656.                contractID : "@mozilla.org/updates/timer-manager;1",
  2657.                className  : "Timer Manager",
  2658.                factory    : #1#(TimerManager)
  2659.              },
  2660.     manager: { CID        : Components.ID("{093C2356-4843-4C65-8709-D7DBCBBE7DFB}"),
  2661.                contractID : "@mozilla.org/updates/update-manager;1",
  2662.                className  : "Update Manager",
  2663.                factory    : #1#(UpdateManager)
  2664.              },
  2665.   },
  2666.   
  2667.   canUnload: function(componentManager) {
  2668.     return true;
  2669.   }
  2670. };
  2671.  
  2672. function NSGetModule(compMgr, fileSpec) {
  2673.   return gModule;
  2674. }
  2675.  
  2676. /**
  2677.  * Determines whether or there are installed addons which are incompatible 
  2678.  * with this update.
  2679.  * @param   update
  2680.  *          The update to check compatibility against
  2681.  * @returns true if there are no addons installed that are incompatible with
  2682.  *          the specified update, false otherwise.
  2683.  */
  2684. function isCompatible(update) {
  2685. //@line 2733 "/var/tmp/portage/mozilla-firefox-1.5.0.3/work/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2686.   var em = 
  2687.       Components.classes["@mozilla.org/extensions/manager;1"].
  2688.       getService(Components.interfaces.nsIExtensionManager);
  2689.   var items = em.getIncompatibleItemList("", update.extensionVersion,
  2690.     nsIUpdateItem.TYPE_ADDON, false, { });
  2691.   return items.length == 0;
  2692. //@line 2742 "/var/tmp/portage/mozilla-firefox-1.5.0.3/work/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2693. }
  2694.  
  2695. /**
  2696.  * Shows a prompt for an update, provided there are no incompatible addons.
  2697.  * If there are, kick off an update check and see if updates are available
  2698.  * that will resolve the incompatibilities.
  2699.  * @param   update
  2700.  *          The available update to show
  2701.  */
  2702. function showPromptIfNoIncompatibilities(update) {
  2703.   function showPrompt(update) {
  2704.     LOG("UpdateService", "_selectAndInstallUpdate: need to prompt user before continuing...");
  2705.     var prompter = 
  2706.         Components.classes["@mozilla.org/updates/update-prompt;1"].
  2707.         createInstance(Components.interfaces.nsIUpdatePrompt);
  2708.     prompter.showUpdateAvailable(update);
  2709.   }
  2710.  
  2711. //@line 2761 "/var/tmp/portage/mozilla-firefox-1.5.0.3/work/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2712.   /**
  2713.    * Determines if an addon is compatible with a particular update.
  2714.    * @param   addon
  2715.    *          The addon to check
  2716.    * @param   version
  2717.    *          The extensionVersion of the update to check for compatibility 
  2718.    *          against.
  2719.    * @returns true if the addon is compatible, false otherwise
  2720.    */
  2721.   function addonIsCompatible(addon, version) {
  2722.     var vc = 
  2723.         Components.classes["@mozilla.org/xpcom/version-comparator;1"].
  2724.         getService(Components.interfaces.nsIVersionComparator);
  2725.     return (vc.compare(version, addon.minAppVersion) >= 0) &&
  2726.           (vc.compare(version, addon.maxAppVersion) <= 0);
  2727.   }
  2728.  
  2729.   /**
  2730.    * An object implementing nsIAddonUpdateCheckListener that looks for 
  2731.    * available updates to addons and if updates are found that will make the 
  2732.    * user's installed addon set compatible with the update, suppresses the
  2733.    * prompt that would otherwise be shown.
  2734.    * @param   addons
  2735.    *          An array of incompatible addons that are installed.
  2736.    * @constructor
  2737.    */
  2738.   function Listener(addons) {
  2739.     this._addons = addons;
  2740.   }
  2741.   Listener.prototype = {
  2742.     _addons: null,
  2743.     
  2744.     /**
  2745.      * See nsIUpdateService.idl
  2746.      */
  2747.     onUpdateStarted: function() { 
  2748.     },
  2749.     onUpdateEnded: function() {
  2750.       // There are still incompatibilities, even after an extension update 
  2751.       // check to see if there were newer, compatible versions available, so
  2752.       // we have to prompt. 
  2753.       // 
  2754.       // PREF_APP_UPDATE_INCOMPATIBLE_MODE controls the mode in which we 
  2755.       // handle incompatibilities:
  2756.       // 0    We count both VersionInfo updates _and_ NewerVersion updates
  2757.       //      against the list of incompatible addons installed - i.e. if
  2758.       //      Foo 1.2 is installed and it is incompatible with the update, and
  2759.       //      we find Foo 2.0 which is but which is not yet downloaded or 
  2760.       //      installed, then we do NOT prompt because the user can download
  2761.       //      Foo 2.0 when they restart after the update during the mismatch
  2762.       //      checking UI. This is the default, since it suppresses most 
  2763.       //      prompt dialogs. 
  2764.       // 1    We count only VersionInfo updates against the list of 
  2765.       //      incompatible addons installed - i.e. if the situation above
  2766.       //      with Foo 1.2 and available update to 2.0 applies, we DO show
  2767.       //      the prompt since a download operation will be required after
  2768.       //      the update. This is not the default and is supplied only as
  2769.       //      a hidden option for those that want it. 
  2770.       var mode = getPref("getIntPref", PREF_APP_UPDATE_INCOMPATIBLE_MODE, 
  2771.                          INCOMPATIBLE_MODE_NEWVERSIONS);
  2772.       if ((mode == 0 && this._addons.length) || !isCompatible(update))
  2773.         showPrompt(update);
  2774.     },
  2775.     onAddonUpdateStarted: function(addon) {
  2776.     },
  2777.     onAddonUpdateEnded: function(addon, status) {
  2778.       if (status == Components.interfaces.nsIAddonUpdateCheckListener.STATUS_UPDATE &&
  2779.           addonIsCompatible(addon, update.extensionVersion)) {
  2780.         for (var i = 0; i < this._addons.length; ++i) {
  2781.           if (this._addons[i] == addon) {
  2782.             this._addons.splice(i, 1);
  2783.             break;
  2784.           }
  2785.         }
  2786.       }
  2787.     },
  2788.     /**
  2789.      * See nsISupports.idl
  2790.      */
  2791.     QueryInterface: function(iid) {
  2792.       if (!iid.equals(Components.interfaces.nsIAddonUpdateCheckListener) &&
  2793.           !iid.equals(Components.interfaces.nsISupports))
  2794.         throw Components.results.NS_ERROR_NO_INTERFACE;
  2795.       return this;
  2796.     }
  2797.   };
  2798.   
  2799.   if (!isCompatible(update)) {
  2800.     var em = 
  2801.         Components.classes["@mozilla.org/extensions/manager;1"].
  2802.         getService(Components.interfaces.nsIExtensionManager);
  2803.     var listener = new Listener(em.getIncompatibleItemList("", 
  2804.       update.extensionVersion, nsIUpdateItem.TYPE_ADDON, false, { }));
  2805.     // See documentation on |mode| above. 
  2806.     var mode = getPref("getIntPref", PREF_APP_UPDATE_INCOMPATIBLE_MODE, 
  2807.                        INCOMPATIBLE_MODE_NEWVERSIONS);
  2808.     em.update([], 0, mode != 0, listener);
  2809.   }
  2810.   else
  2811. //@line 2861 "/var/tmp/portage/mozilla-firefox-1.5.0.3/work/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2812.     showPrompt(update);
  2813. }
  2814.